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[]{})
.
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.
Yes we can call static methods using object references. We can call them using object reference as well as class name.
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.
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);
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