Archived

This topic is now archived and is closed to further replies.

silencer

[java] How to get the Class object form a static method ?

Recommended Posts

Consider the following code : public class MyClass { public void myFunction() { Class c=this.getClass(); // This will retrieve the class of the object on which the method in invoked } } Now I would like to get the Class but from a static method : public class MyClass { public static void myFunction() { Class c= ??? } } For now, I am just using : Class c=MyClass.class; But I am pretty sure there is another way, a bit more generic. Herve

Share this post


Link to post
Share on other sites
Static methods are completely removed from objects, that''s their definition. The only way to call a static method is from it''s class so there should be no point in your code where you can call a static method w/o knowing the class. Objects are different, I can cast them to different interfaces or superclasses, I can read them in from a stream... retrieving an object''s class is sensible, retrieving a staic method''s class is not.

You can use java.lang.Class.forName(String) to get a class for which you know the name. Note that this is a static method of class Class so you do not have to have a Class object, you only need to know the name of the class.

Share this post


Link to post
Share on other sites