如何使用LambdaMetaFactory实例化对象? [英] How to instantiate an object using LambdaMetaFactory?

查看:695
本文介绍了如何使用LambdaMetaFactory实例化对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个操作界面:

package action;

public interface Action {
    public String act();
}

SimpleAction类:

Class 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类:

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

我想创建一个使用类名称并返回该类对象的函数. 这就是我到目前为止的功能-

I want to create a function which takes the name of class and returns an object of that class. This is what I have so far in my function -

 

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

这篇关于如何使用LambdaMetaFactory实例化对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆