J
Jimi Hullegård
Lets say I have a class MyClass, that is final, and has a private
constructor. So I can't instantiate it.
Now, if I want to call a static method myMethod("hello"), I simply do
MyClass.myMethod("hello"). This is all basic stuff.
But what if I want to pass MyClass to another method, and from there call
myMethod("hello")?
This is what I thought would be possible, but it isn't:
....
doTest(MyClass.getClass(), "hello");
....
public void doTest(Class<MyClass> mc, String message)
{
mc.myMethod(message);
}
This results in:
java.lang.ClassCastException: java.lang.Class
Why doesn't this work? Is there a way to represent MyClass as a real class
(not a Class<MyClass> object), so I can call mc.myMethod(message) on it?
Is there no way to call a static method on a class object without using
reflection? If the class could be instantiated it would be easy to call the
method on that object, but even then it seems stupid to instantiate an
object just to call on a static method.
Regards
/Jimi
constructor. So I can't instantiate it.
Now, if I want to call a static method myMethod("hello"), I simply do
MyClass.myMethod("hello"). This is all basic stuff.
But what if I want to pass MyClass to another method, and from there call
myMethod("hello")?
This is what I thought would be possible, but it isn't:
....
doTest(MyClass.getClass(), "hello");
....
public void doTest(Class<MyClass> mc, String message)
{
mc.myMethod(message);
}
This results in:
java.lang.ClassCastException: java.lang.Class
Why doesn't this work? Is there a way to represent MyClass as a real class
(not a Class<MyClass> object), so I can call mc.myMethod(message) on it?
Is there no way to call a static method on a class object without using
reflection? If the class could be instantiated it would be easy to call the
method on that object, but even then it seems stupid to instantiate an
object just to call on a static method.
Regards
/Jimi