Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8291672

Protected scope problem in static method or static variable

XMLWordPrintable

      A DESCRIPTION OF THE PROBLEM :
      The demo code is as follows:
      package com.feilong.test.demo;

      public class Parent {

          protected static int count;

          protected static int getCount(){
              return count;
          }

      }

      package com.feilong.test.demo.ch;

      import com.feilong.test.demo.Parent;

      public class Child extends Parent {

          public static void main(String[] args) throws Exception{
              System.out.println(Parent.count); // will print 0
              System.out.println(Parent.getCount()); // will print 0

              // will throw Exception:
              // Exception in thread "main" java.lang.IllegalAccessException: Class com.feilong.test.demo.ch.Child can not access a member of class com.feilong.test.demo.Parent with modifiers "protected static"
              // at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
              // at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
              // at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
              // at java.lang.reflect.Field.get(Field.java:390)
              // at com.feilong.test.demo.ch.Child.main(Child.java:10)
              System.out.println(Parent.class.getDeclaredField("count").get(null));
              System.out.println(Parent.class.getDeclaredMethod("getCount").invoke(null));
          }

      }

      The code executed by reflection did not achieve the expected effect and an exception was thrown.The reason is that there is no distinction between whether the executed target is static or not.


      FREQUENCY : always


        1. Child.java
          1 kB
          Andrew Wang
        2. Parent.java
          0.2 kB
          Andrew Wang

            rpallath Rajendrakumar Pallath
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            4 Start watching this issue

              Created:
              Updated: