Pregunta

When calling "main" that exists in another class, it is quite easy to just say:

 otherClass.main(stringArgs);

What is the reason behind first using reflection to get the class and then invoking the method, other than calling it in a static manner?

¿Fue útil?

Solución

A reason might be that if you use reflection, you do not need to have a compile-time dependency on the class that you are invoking the main method of. You can load the class dynamically, using Class.forName(...), then use reflection to find the main method and invoke it.

String name = "com.mycompany.MyMainClass";

// Load the class dynamically
Class<?> mainClass = Class.forName(name);

// Find the 'main' method that takes a string array
Method mainMethod = mainClass.getMethod("main", new Class<?>[] { String[].class });

// Invoke the method; first arg is null, because the method is static
mainMethod.invoke(null, new String[] { "one", "two" });

Otros consejos

I don't know why you're doing this ever. I've never needed to invoke another main method in this way except when I was doing something hacky or experimenting.

But generally you use reflection to call a method instead of calling it directly when you don't know enough about the class you're invoking, or for when you're searching and invoking methods marked with annotation.

That's what reflection was meant for.

There are numerous reasons to use reflection. But if you have an instance of a class (or the name of a class if we're talking about a static method) and know the name of the method you want to call (during compile-time), you shouldn't use reflection.

To give you an example, one reason to use reflection is if you, for some reason, have a String containing a method name (let's say you get this from the user) and want to call this method of a specific class. You obviously can't just say otherClass.methodName since methodName will differ depending on what the user inputs.

In most use cases where the need to call main arises at all, it is in the context where the class is not know at build time, and is probably not even inside the codebase thae does the call. This may be the reason why you most often witness reflective calls of main.

Indeed, calling main statically makes quite little sense.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top