Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling static method on a class?

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.

like image 802
yanchenko Avatar asked Jun 02 '09 22:06

yanchenko


People also ask

How do you call a static method in class?

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().

How do you call a static method from a class in Java?

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.

Can we call static method with class object?

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.

Can we call static method in Java?

In Java, we cannot call the static function by using the object. It is invoked by using the class name.


1 Answers

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");
like image 165
Alex Beardsley Avatar answered Oct 12 '22 14:10

Alex Beardsley