How to save class reference in Java?

Is there a way in Java to store a reference to a class? Here is what I want to do:

public class Foo
{
    public static void doSomething() {...}
};

SomeClass obj = Foo;
obj.doSomething();

Is there any "SomeClass" class that allows me to store a reference to the class so that I can later use this stored object to call the static member of the original class?

The Class class will be obvious:

Class obj = Foo.class;
obj.someMember().doSomething();

but I didn’t understand which member of the class class can act as "someMember ()" ... none of them, I think.

Does anyone know if it is possible that I am trying to do in Java?

+3
source share
2 answers

You can dynamically get a method from a class object using the getMethod () methods in the class. If the method is static, then the "object" parameter for "invoke" will be empty.

, "obj.someMember()" :

obj.getMethod("someMember", null).invoke(null, null);

- , . , .

, .

. , , doSomething().

, , .:)

+5

jdk1.5 , , .

0

Source: https://habr.com/ru/post/1776817/


All Articles