Why calling method with generic return on a generic class is considered unsafe by javac?

后端 未结 4 1687
南笙
南笙 2020-12-06 16:42

Consider the following code:

public class Main {
    public static class NormalClass {
        public Class method() {
            return Inte         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 17:06

    This might have to do with the instantiation of GenericClass which is a parameterized type and hence type arguments are needed in it. The warning vanishes if we do something like the following

    GenericClass unsafeInstance = new GenericClass();
                              OR
    GenericClass unsafeInstance = new GenericClass();
    

    As per my point of view, the reference "unsafeInstance" refers to a class which is generic in nature as opposed to "safeInstance". Thus the compiler may want the type information be associated to the reference before any method is called using it in code.

提交回复
热议问题