I am tying to resolve type on runtime with generics. Here is my code.
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");
}
}
How do I utilize/call methods print(String string),print(Integer integer) in generic class.
Even I have tried
stringVerify.obj = new String();
stringVerify.call();
which is calling same method with object signature.
Also tried following, which is also invoking same method with object signature.
Verify<String> stringVerify = new Verify<String>() {};
stringVerify.obj = new String();
stringVerify.call();
for all above scenarios output will be.
Obj
string
Int
Obj
Obj
Obj
Following is what I want
Obj
string
Int
Obj
string
Int
please educate me.
Generics type erasure. In your case generic type
<T>
erased toObject
.For more information read this documentation
https://docs.oracle.com/javase/tutorial/java/generics/erasure.html
Sorry for my bad English.