How to read the value of a private field from a different class in Java?

前端 未结 14 1704
梦毁少年i
梦毁少年i 2020-11-21 11:28

I have a poorly designed class in a 3rd-party JAR and I need to access one of its private fields. For example, why should I need to choose priv

14条回答
  •  忘了有多久
    2020-11-21 12:04

    Using the Reflection in Java you can access all the private/public fields and methods of one class to another .But as per the Oracle documentation in the section drawbacks they recommended that :

    "Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform"

    here is following code snapts to demonstrate basic concepts of Reflection

    Reflection1.java

    public class Reflection1{
    
        private int i = 10;
    
        public void methoda()
        {
    
            System.out.println("method1");
        }
        public void methodb()
        {
    
            System.out.println("method2");
        }
        public void methodc()
        {
    
            System.out.println("method3");
        }
    
    }
    

    Reflection2.java

    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    
    public class Reflection2{
    
        public static void main(String ar[]) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException
        {
            Method[] mthd = Reflection1.class.getMethods(); // for axis the methods 
    
            Field[] fld = Reflection1.class.getDeclaredFields();  // for axis the fields  
    
            // Loop for get all the methods in class
            for(Method mthd1:mthd)
            {
    
                System.out.println("method :"+mthd1.getName());
                System.out.println("parametes :"+mthd1.getReturnType());
            }
    
            // Loop for get all the Field in class
            for(Field fld1:fld)
            {
                fld1.setAccessible(true);
                System.out.println("field :"+fld1.getName());
                System.out.println("type :"+fld1.getType());
                System.out.println("value :"+fld1.getInt(new Reflaction1()));
            }
        }
    
    }
    

    Hope it will help.

提交回复
热议问题