我想用泛型在运行时解析类型。这是我的代码。
public class NewClas {
public static void main(String[] args) {
Object object = null;
String string = null;
Integer integer = null;
// with out generics
print(object);
print(string);
print(integer);
// print(null); // this won't complile
// with generics
Verify<Object> objectVerify = new Verify<Object>();
Verify<String> stringVerify = new Verify<String>();
Verify<Integer> integerVerify = new Verify<Integer>();
objectVerify.call();
stringVerify.call();
integerVerify.call();
}
public static void print(Object obj) {
System.out.println("Obj");
}
public static void print(String string) {
System.out.println("string");
}
public static void print(Integer integer) {
System.out.println("Int");
}
}
// if T extends String then only print(String string) will call
class Verify<T> {
public T obj = null;
public void call() {
print(obj);
}
// even this is not working
/*public <T> void call() {
print((T)obj);
}*/
public void print(Object obj) {
System.out.println("Obj");
}
public void print(String string) {
System.out.println("string");
}
public void print(Integer integer) {
System.out.println("Int");
}
}
如何在泛型类中使用/调用方法 print(String string),print(Integer integer)。
即使我尝试过
stringVerify.obj = new String();
stringVerify.call();
这是使用对象签名调用相同的方法。
还尝试了以下操作,它也使用对象签名调用相同的方法。
Verify<String> stringVerify = new Verify<String>() {};
stringVerify.obj = new String();
stringVerify.call();
对于所有上述情况,输出将是。
Obj
string
Int
Obj
Obj
Obj
以下是我想要的
Obj
string
Int
Obj
string
Int
请教育我。