how to get a constant in java with class

后端 未结 6 1293
一个人的身影
一个人的身影 2021-02-13 14:51

basically I need to get a constant for a class however I have no instance of the object but only its class. In PHP I would do constant(XYZ); Is there a similar way

相关标签:
6条回答
  • 2021-02-13 15:23

    If you don't want to actually load or initialize the class, ClassGraph can do this:

    String fieldVal;
    try (ScanResult scanResult =
            new ClassGraph().whitelistClasses(className).enableFieldInfo().scan()) {
        fieldVal = (String) scanResult.getClassInfo(className).getFieldInfo("s")
                .getConstantInitializerValue();
    }
    

    N.B. this works only for constant initializer values (values that can be computed without object instantiation, with the exception of String), assigned to static final fields. The compiler can produce a constant at compiletime for simple arithmetic and simple string concatenation.

    (disclaimer, I am the author of ClassGraph)

    Simply using reflection to access static fields is simpler, if you don't mind loading the class, as given in this other answer: https://stackoverflow.com/a/4076792/3950982

    0 讨论(0)
  • 2021-02-13 15:24

    To get private constant like:

    private static final String BAR = "test";
    

    you need to set it accessible first:

    Field barField = Foo.class.getDeclaredField("BAR");
    barField.setAccessible(true);
    String bar = (String) barField.get(null);
    
    0 讨论(0)
  • 2021-02-13 15:33

    If this constant is metadata about the class, I'd do this with annotations:

    First step, declare the annotation:

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @interface Abc {
        String value(); 
    }
    

    Step two, annotate your class:

    @Abc("Hello, annotations!")
    class Zomg {
    
    }
    

    Step three, retrieve the value:

    String className = "com.example.Zomg";
    Class<?> klass = Class.forName(className);
    Abc annotation = klass.getAnnotation(Abc.class);
    String abcValue = annotation.value();
    System.out.printf("Abc annotation value for class %s: %s%n", className, abcValue);
    

    Output is:

    Abc annotation value: Hello, annotations!
    0 讨论(0)
  • 2021-02-13 15:34

    You might look for sth. like
    Foo.class.getDeclaredField("THIS_IS_MY_CONST").get(null); or Class.forName("Foo").getDeclaredField("THIS_IS_MY_CONST").get(null); (thanks f-o-o)

    Gets the value of a String constant (THIS_IS_MY_CONST) in class Foo.

    Update use null as argument for get thanks acdcjunior

    0 讨论(0)
  • 2021-02-13 15:40

    I am not sure what you want to get out. But it shouldn't be too difficult to show you an example.

    Lets say you have a Class Foo with property bar.

    Class Foo {
        private final String bar = "test";
        public String getBar() {return bar;}
    }
    

    Now to get this through reflection you would:

    Class fooClass = Foo.class;
    Object fooObj = fooClass.newInstance();
    Method fooMethod = fooClass.getMethod("getBar");
    String bar = (String) fooMethod.invoke(fooObj);
    

    Now you will get value of method getBar() in bar variable

    0 讨论(0)
  • 2021-02-13 15:45

    Maybe I don't understand what you need, but did you try with final static attributes and static methods?

    Final means that it can't be changed once set, so you get a constant. Static means it's accessible even if there aren't any objects of the class.

    0 讨论(0)
提交回复
热议问题