我正在使用一个工具,它为我使用的不同结构生成不同的类
例如,它可能会创建两个这样的类
class TypeSupportImpl {
void callme()
{
System.out.println("I an here");
}
void test()
{
}
}
public class StringReader extends TypeSupportImpl
{
void callme()
{
System.out.println("HelloReader an here");
}
void test()
{
}
public static String get_name() {
String s = "hello";
return s ;
}
}
public class HelloReader extends TypeSupportImpl
{
void callme()
{
System.out.println("HelloReader an here");
}
void test()
{
}
public static String get_name() {
String s = "hello";
return s ;
}
}
现在我想为此类编写一个通用包装器。我希望通用包装器的行为方式是,如果用户将 Hello
作为类型传递,它应该创建 Helloreader
对象。如果用户使用 String
,则应创建一个 StringReader
对象。
public class TestCode<T > {
//if T= Hello
HelloReader.get_name();
//if T== String
StringReader.get_name()
}
您能否建议如何在不使用反射的情况下实现它的最佳方式。
最佳答案
即使有反射(reflection),你也根本做不到。类型删除意味着在运行时,您将无法看到类型参数是什么,即使您将其作为参数传递(请参阅 EnumSet
的构建器),您也会使用反射,因为 static
元素在编译时绑定(bind)到特定类型。
关于java - 需要根据泛型类中的类型创建不同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21711033/