gpt4 book ai didi

使用反射使用任何构造函数实例化任何类的 Java 泛型方法

转载 作者:行者123 更新时间:2023-11-29 07:13:48 27 4
gpt4 key购买 nike

我们知道 Java 使用删除,所以任何泛型类都做不到

T t = new T();

所以我尝试使用 Java 反射来创建一个具有静态方法的类,以使用任何构造函数实例化任何类。这是代码。

import java.lang.reflect.*;

public class GenericNewInstance {
public static <T> T createInstance(Class<T> cObj) {
try {
return cObj.newInstance();
} catch (InstantiationException e) {
System.out.println("Instantiation Exception");
return null;
} catch (IllegalAccessException e) {
System.out.println("Illegal Access Exception");
return null;
}
}

public static <T> T createInstanceUsingRelection(Class<T> c, Object... initArgs) {
Constructor<T> cTor = null;
Class<?>[] cObjs = new Class<?>[initArgs.length];
int i = 0;

for(Object o : initArgs) {
cObjs[i++] = o.getClass();
}

try {
cTor = c.getConstructor(cObjs);
} catch (SecurityException e) {
System.out.println("security exception. Cannot get Constructor");
return null;
} catch (NoSuchMethodException e) {
System.out.println("NoSuchMethodException Cannot get constructor");
return null;
}

try {
return cTor.newInstance(initArgs);
} catch (IllegalArgumentException e) {
System.out.println("Illegal Argument Exception");
return null;
} catch (InstantiationException e) {
System.out.println("Instantiation Exception");
return null;
} catch (IllegalAccessException e) {
System.out.println("Illegal Access Exception");
return null;
} catch (InvocationTargetException e) {
System.out.println("Invocation Target Exception");
return null;
}
}
}

使用这个的例子。

Integer i = GenericNewInstance.createInstanceUsingRelection(Integer.class, "0");

所以我的问题:

  1. 这是实现它的正确方法吗? (还是冗长?)
  2. 这样做的典型用例是什么?
  3. 我们可以/应该在使用泛型时避免使用反射吗?

最佳答案

您的代码将在 c.getConstructor(cObjs) 处失败,因为这没有考虑类型层次结构。如果任何参数是构造函数声明的参数类型的子类型,则此调用不会返回它。您将需要更多的类型杂耍才能使其正常工作。我建议你看看code that already solves this problem .也许您甚至可以按原样使用该库,您可以选择。它是 Clojure 的实现代码,Clojure 是一种基于 JVM 的动态语言,正是需要这些东西。该库可从 Maven 中央存储库获得。

顺便说一句,您的异常处理是多余的。要么只声明 throws Exception,要么捕获任何 Exception 并将其包装在 RuntimeException 中。当出现故障时,原始异常是最好的诊断。

关于使用反射使用任何构造函数实例化任何类的 Java 泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11486886/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com