-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.

4

2 回答 2

1

Class.forName您可以使用该方法加载一个类。

例如

(Cast) Class.forName("fully.qualified.class.Name").newInstance().yourMethod()

(Cast) - 可以是 yourMethod() 的类型

于 2013-05-25T20:34:27.113 回答
1

给定这样的类:

public class Foo
{
    public void bar()
    {
        System.out.println("Foo.bar");
    }

    public void car()
    {
        System.out.println("Foo.car");
    }
}

和这样的代码:

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 */);
    }
}

你可以这样运行:

java Main Foo bar
java Main Foo car

它会根据需要调用 foo 或 bar 方法。

于 2013-05-25T20:42:32.753 回答