Generic Class with Constraint access issue

前端 未结 2 921
耶瑟儿~
耶瑟儿~ 2021-02-14 22:51

This a general JAVA question. In android, there is an interface Parcelable:

This is an example inside the official documentation:

 public class MyParcela         


        
2条回答
  •  既然无缘
    2021-02-14 23:25

    Instead of you need & Parcelable> this way you specify that T is ShushContainer so you can access is methods and variables.

    public class ShushContainer & Parcelable> 
    implements Parcelable
    

    Here is the example using Serializable

    class Sample & Serializable> implements Serializable {
    
      public static int CONST = 0;
    
       public void foo()
       {
         T.CONST = 5;
       }
    }
    

    Update

    If I understand correctly threre is another class which implements Parcelable which has CREATOR You are trying dynamic polymorphism for Static variables which is not possible.

    Sample example to show how it fails

    public class Base {
        public static int count = 10;
    }
    
    public class Child extends Base {
        public static int count = 20;
    }
    
    
    class Sample {
        T t = null;
        public void printCount() {
            System.out.println(T.count);
        }
        public Sample(T t) {
            this.t = t;
        }
    
        public static void main(String[] args) {
            Sample sample = new Sample(new Child());
            Sample sample1 = new Sample(new Base());
            sample.printCount();//Child value printed as 10
            sample1.printCount();//Same for parent value printed as  10
        }
    
    }
    

    This program fails because static fields are bound to Class rather than instance so there are two separate count one for Base and one for Child if you access value of Base then it will always be 10.

    You can use reflection to check whether CREATOR field is present and access it.Which will not be possible without object or class object.

    Or You can do something like below using TypeToken

    class Sample implements Serializable {
    
        public int abc = 0;
        public void foo() {
        }
        public static void main(String[] args) throws SecurityException, NoSuchFieldException {
            TypeToken> token = new TypeToken>() {
            };
            Class t = token.getRawType();
            Field field = t.getDeclaredField("abc");
            field.setAccessible(true);
            System.out.println(field.getName());
    
        }
    }
    

提交回复
热议问题