[英]How to instantiate an object using LambdaMetaFactory?
I have an interface Action: 我有一个接口Action:
package action;
public interface Action {
public String act();
}
Class SimpleAction: 类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;
}
}
Class ComplexAction: 类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));
}
Figured it out. 弄清楚了。
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;
}
You can do just this, it will give you an object, using the constructor with no arguments: 您可以做到这一点,它将使用不带参数的构造函数为您提供一个对象:
public static Object resultOfActMethod(String objclass)
throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class<?> clazz = Class.forName(objclass);
return clazz.getConstructor().newInstance();
}
But if possible in your application, you should make a function which takes a class instead like this: 但是,如果可能的话,您应该在应用程序中创建一个采用类的函数,如下所示:
public static <C> C resultOfActMethod(Class<C> clazz)
throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
return clazz.getConstructor().newInstance();
}
This is typesafe. 这是类型安全的。 You can use a specific return type. 您可以使用特定的返回类型。 This will avoid a type cast at the caller's side. 这样可以避免在调用方使用强制类型转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.