-2

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.

Paul
  • 21
  • 3

2 Answers2

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