如何使用LambdaMetaFactory实例化对象?

时间:2018-12-07 19:31:35

标签: java lambda java-8 invokedynamic lambda-metafactory

我有一个操作界面:

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

ComplexAction类:



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

2 个答案:

答案 0 :(得分:2)

想通了。

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

答案 1 :(得分:0)

您可以执行此操作,它将使用不带参数的构造函数为您提供一个对象:

const styles = {
  control: (base) => ({
    ...base,
    minHeight: 32,
  }),
  dropdownIndicator: (base) => ({
    ...base,
    paddingTop: 0,
    paddingBottom: 0,
  }),
  clearIndicator: (base) => ({
    ...base,
    paddingTop: 0,
    paddingBottom: 0,
  }),
};

<Select styles={styles}/>

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

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

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