简体   繁体   中英

How to store a reference to a class in Java?

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

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

SomeClass obj = Foo;
obj.doSomething();

Is there some class "SomeClass" which lets me store a reference to a class, such that I can later use that stored object to call a static member of the original class?

The obvious thing would be class Class:

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

but I haven't figured out which of class Class's members might act as "someMember()"... none of them, I think.

Does anyone know if what I'm trying to do is possible in Java?

You can dynamically get a method from a Class object using the getMethod() methods on the class. If a method is static, then the "object" parameter of "invoke" will be null.

For example, the "obj.someMember()" above would be something like this:

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

The extra nulls are because your method requires no parameters. If your method takes parameters, then they will need to be passed in accordingly.

This will throw various checked exceptions, so you'll need to handle those as well.

Once you've invoked the method, it will return an Object. You'll want to cast that to whatever type you're expecting, and then you'll be able to run the "doSomething()" method directly on that.

This is using a trick called reflection, if you'd like to read up more on it. :)

如果您使用的是jdk1.5或更高版本,则在您想要获取Class的元数据时,可以选择注释

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM