Using generic type security in Java

I encountered generic behavior in Java and I didn't understand it at all (using my. Net background)

public class TestGeneric<T>
{
    public void get (Object arg)
    {
        T temp = (T) arg;

        System.out.println(temp.toString());

        return;
    }
}

TestGeneric<Integer> tg = new TestGeneric<Integer>();
tg.get("Crack!!!");

Please tell me why I won't get ClassCastException. Moreover, in idea, I see that temp is string and has "crack!!!" The value of the Besides, how can I throw ClassCastException? I use JDK 1.7.0 on Windows 7 X64 0_ seven

Solution

The reason you don't get a class conversion exception is that Java generics are implemented through type erasure And those requiring significant changes to the CLS Net generics library, Java generics are handled completely at compile time At runtime, the conversion to t is ignored In order to check the type at run time, you need to store class < T > and use its methods to check the type of the passed in parameters:

public class TestGeneric<T>
{
    private Class<T> genClass;
    public TestGeneric(Class<T> t) {genClass = t;}
    public void get (Object arg)
    {
        if (!genClass.isinstance(arg)) {
            throw new ClassCastException();
        }
        T temp = (T) arg;

        System.out.println(temp.toString());

        return;
    }
}

TestGeneric<Integer> tg = new TestGeneric<Integer>(Integer.class);
tg.get("Bang!!!"); // Now that's a real Bang!!!
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>