如何使用 LambdaMetaFactory 实例化一个对象?

How to instantiate an object using LambdaMetaFactory?

我有一个接口操作:

package action;

public interface Action {
    public String act();
}

Class简单动作:


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;
    }
}

Class 复杂动作:



    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;
        }
    }

我想创建一个函数,其名称为 class,returns 是 class 的一个对象。 这是我目前的职能 -

 

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

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

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

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

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

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

想通了。

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;
}