Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call static method given a class object in java

Tags:

java

If

class MyClass {
    public static void main(String[] str) {
        System.out.println("hello world");
    }
}

// in some other file and method
Class klass = Class.forName("MyClass");

How can I call MyClass.main? I do not have the string "MyClass" at compile time, so I cannot simply call MyClass.main(String[]{}).

like image 381
Aaron Yodaiken Avatar asked Jan 28 '12 03:01

Aaron Yodaiken


People also ask

Can we call static method with class object in Java?

Static Method 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 you call static method by class object?

Yes we can call static methods using object references. We can call them using object reference as well as class name.

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

Call a static Method in Another Class in Java In the case of a static method, we don't need to create an object to call the method. We can call the static method by using the class name as we did in this example to call the getName() static method.


1 Answers

You use reflection to invoke methods (or create objects etc). Below is a sample to invoke main() method in MyClass. All you need to make sure is that MyClass is in the classpath.

Class<?> cls = Class.forName("MyClass");
Method m = cls.getMethod("main", String[].class);
String[] params = null; 
m.invoke(null, (Object) params); 
like image 97
Aravind Yarram Avatar answered Nov 10 '22 14:11

Aravind Yarram