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[]{}).
You use reflection to invoke methods (or create objects etc). Below is a sample to invoke
main()method inMyClass. All you need to make sure is thatMyClassis in the classpath.