I have seen a lot of stuff here about reflection to load a class and such, I just do not think that this is what I am looking for. Basically, what I want is a way to load a method from a class dynamically. So like: loadDynamicClass("NameFromString").onStart(); where onStart() is a method in each of the classes I am trying to load. If there is something on stackoverflow I missed, just mark this as a duplicate.
Asked
Active
Viewed 203 times
-2
-
1Not entirely sure what the question is. You want to choose a class at runtime based on a string? – mwerschy May 25 '13 at 20:30
-
Pretty much, and then use a method from it. – Paul May 25 '13 at 20:32
-
Class.forName, then newInstance and then cast to some general type that has that method on it – cmbaxter May 25 '13 at 20:34
-
Take a look at [this](http://stackoverflow.com/questions/2621251/java-reflection) which illustrates method invocation by name using reflection. – ashatch May 25 '13 at 20:36
2 Answers
1
You can load a class with the Class.forName
method.
E.g.
(Cast) Class.forName("fully.qualified.class.Name").newInstance().yourMethod()
(Cast) - can be of a type that yourMethod()

Dhrubajyoti Gogoi
- 1,265
- 10
- 18
1
Given a class like this:
public class Foo
{
public void bar()
{
System.out.println("Foo.bar");
}
public void car()
{
System.out.println("Foo.car");
}
}
and code like this:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main
{
public static void main(final String[] argv)
throws ClassNotFoundException,
NoSuchMethodException,
InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
final Class<?> clazz;
final Method method;
final Object instance;
clazz = Class.forName(argv[0]);
method = clazz.getMethod(argv[1] /*, types */);
instance = clazz.newInstance();
method.invoke(instance /*, arguments */);
}
}
You can run like this:
java Main Foo bar
java Main Foo car
and it will call the foo or bar method as desired.

TofuBeer
- 60,850
- 18
- 118
- 163