Say, I have a reference to a Class object with SomeType having a static method. Is there a way to call that method w/o instantiating SomeType first? Preferably not escaping strong typing.
EDIT: OK, I've screwed up.
interface Int{
void someMethod();
}
class ImplOne implements Int{
public void someMethod() {
// do something
}
}
Class<? extends Int> getInt(){
return ImplOne.class;
}
In this case someMethod() can't be static anyways.
A static method can be called from either a class or object reference. We can call it Utils if foo() is a static function in Class Utils. Utils. foo() as well as Utils().
A static method can be called directly from the class, without having to create an instance of the class. A static method can only access static variables; it cannot access instance variables. Since the static method refers to the class, the syntax to call or refer to a static method is: class name. method name.
Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.
In Java, we cannot call the static function by using the object. It is invoked by using the class name.
I'm not sure exactly what the situation is, but if you're looking to execute the static method on a class without knowing the class type (i.e. you don't know it's SomeType, you just have the Class object), if you know the name and parameters of the method you could use reflection and do this:
Class c = getThisClassObjectFromSomewhere();
//myStaticMethod takes a Double and String as an argument
Method m = c.getMethod("myStaticMethod", Double.class, String.class);
Object result = m.invoke(null, 1.5, "foo");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With