Below code throws a java.lang.ClassCastException if I directly use returned object of t.getTheString(implClass.class) in System.out.println() . Although when I assign object to some reference , it works fine, Why ?
interface testInterface{
public String testMethod();
}
class testClass{
public <T extends testInterface> T getTheString(Class< ? extends testInterface> classType){
try {
testInterface obj = classType.newInstance();
return (T)obj;
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
class implClass implements testInterface{
@Override
public String testMethod() {
return "Sample String";
}
@Override
public String toString(){
return super.toString() + " Overridden toString()";
}
}
public class genericTest {
public static void main(String args[]){
testClass t = new testClass();
testInterface ti = t.getTheString(implClass.class);
implClass i = t.getTheString(implClass.class);
//System.out.println(i); //<= Works fine
//System.out.println(ti); //<= Works fine
System.out.println(t.getTheString(implClass.class)); // Exception in thread "main" java.lang.ClassCastException: implClass cannot be cast to java.lang.String
}
}
Edit: Many people are getting confused with the question. The use of upper bound is just to create this example . I know this is incorrect . The doubt is , if you decompile above code , you will see the compiler typecast the t.getTheString(implClass.class) result to String because may be it is unsure of the type probably . My question is wont it be better if it is typecast to Object . In that case it will call toString() method and code will work fine . Is this an issue with Java Compiler or am i missing any thing here ?