how to get a constant in java with class

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

提交回复
热议问题