24

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[]{}).

1
  • Reflection and class loading can do this. Can you tell us the motivation behind this? Commented Jan 28, 2012 at 3:45

1 Answer 1

51

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

I would NOT call a main entry-point method passing it a null argument. The java launcher calls main with an empty array if there are no command line arguments, and most main methods don't bother to check for null.
@StephenC thanx for the info on java launcher. I didn't know that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.