2

我有一个界面动作:

package action;

public interface Action {
    public String act();
}

类 SimpleAction:


package action;

public class SimpleAction implements Action {

    String action;
    public SimpleAction() {}

    public SimpleAction(String x) {
        this.action = x;
    }

    @Override
    public String act() {
        return "Act method from -" + this.action;
    }
}

类复杂动作:



    package action;

    public class ComplexAction implements Action{

        String action;
        public ComplexAction() {}
        public ComplexAction(String x) {
            this.action = x;
        }
        @Override
        public String act() {
            return "Act method from -" + this.action;
        }
    }

我想创建一个函数,它采用类的名称并返回该类的对象。这就是我迄今为止在我的职能中所拥有的 -

 

    public static Action resultOfActMethod(String objclass){   
        Class clazz = Class.forName(objclass);
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodHandle mh = lookup.findConstructor(clazz,MethodType.methodType(void.class, String.class));
    }

4

2 回答 2

3

弄清楚了。

public static Action resultOfActMethod(String objclass){    
    Class clazz = Class.forName(objclass);
    MethodHandles.Lookup lookup = MethodHandles.lookup();
    MethodHandle mh = lookup.findConstructor(clazz, MethodType.methodType(void.class, String.class));
    Function<String, Action> constructor = (Function<String, Action>)LambdaMetafactory.metafactory(lookup, "apply",MethodType.methodType(Function.class),
                        mh.type().generic(), mh, mh.type()).getTarget().invokeExact();
    Action action = constructor.apply(objclass);
    return action;
}
于 2018-12-07T22:21:13.547 回答
0

你可以这样做,它会给你一个对象,使用不带参数的构造函数:

public static Object resultOfActMethod(String objclass) 
    throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
  Class<?> clazz = Class.forName(objclass);
  return clazz.getConstructor().newInstance();
}

但是如果可能在您的应用程序中,您应该创建一个采用类的函数,而不是像这样:

public static <C> C resultOfActMethod(Class<C> clazz) 
    throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
  return clazz.getConstructor().newInstance();
}

这是类型安全的。您可以使用特定的返回类型。这将避免在调用方进行类型转换。

于 2018-12-07T19:58:12.793 回答