how to get a constant in java with class

后端 未结 6 1285
一个人的身影
一个人的身影 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: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!

提交回复
热议问题