📜  如何在Java中使用反射访问私有字段和方法?

📅  最后修改于: 2022-05-13 01:55:51.929000             🧑  作者: Mango

如何在Java中使用反射访问私有字段和方法?

如果我们想使用反射访问私有字段和方法,我们只需要在要访问的字段或方法对象上调用setAccessible(true)Class.getDeclaredField(String fieldName ) 或Class.getDeclaredFields()可用于获取私有字段。而 Class.getDeclaredMethod(String methodName, Class... parameterTypes) 或 Class.getDeclaredMethods() 可用于获取私有方法。

下面的程序可能无法在在线 IDE 上运行,例如,只能在离线 IDE 上编译和运行以下程序。

1.访问私有字段

Java
// Access Private Field Using Reflection in Java
import java.lang.reflect.Field;
  
// Student class declaration
class Student {
  
    // private fields
    private String name;
    private int age;
  
    // Constructor
    public Student(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
  
    // Getters and setters
    public String getName() { return name; }
  
    public void setName(String name) { this.name = name; }
  
    private int getAge() { return age; }
  
    public void setAge(int age) { this.age = age; }
  
    // Override toString method to get required
    // output at terminal
    @Override public String toString()
    {
        return "Employee [name=" + name + ", age=" + age
            + "]";
    }
}
  
// Program will throw an exception on online IDE
// Compile and run the program on offline IDE
class GFG {
  
    public static void main(String[] args)
    {
        try {
  
            // Student object created
            Student e = new Student("Kapil", 23);
  
            // Create Field object
            Field privateField
                = Student.class.getDeclaredField("name");
  
            // Set the accessibility as true
            privateField.setAccessible(true);
  
            // Store the value of private field in variable
            String name = (String)privateField.get(e);
  
            // Print the value
            System.out.println("Name of Student:" + name);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}


Java
// Access Private Method Using Reflection in Java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
  
// Student class declaration
class Student {
  
    // Private fields
    private String name;
    private int age;
  
    // Constructor
    public Student(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
  
    // Getters and Setters
    public String getName() { return name; }
  
    public void setName(String name) { this.name = name; }
  
    private int getAge() { return age; }
  
    public void setAge(int age) { this.age = age; }
  
    // Override to string method to get
    // Required output when called
    @Override public String toString()
    {
        return "Employee [name=" + name + ", age=" + age
            + "]";
    }
}
  
class GFG {
  
    public static void main(String[] args)
    {
        try {
            // Student class object
            Student e = new Student("Kapil", 23);
  
            // Create Method object
            Method privateMethod
                = Student.class.getDeclaredMethod("getAge");
  
            // Set the accessibility as true
            privateMethod.setAccessible(true);
  
            // Store the returned value of
            // private methods in variable
            int age = (int)privateMethod.invoke(e);
            System.out.println("Age of Student: " + age);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}


输出:

Name of Student:Kapil

2.访问私有方法

Java

// Access Private Method Using Reflection in Java
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
  
// Student class declaration
class Student {
  
    // Private fields
    private String name;
    private int age;
  
    // Constructor
    public Student(String name, int age)
    {
        this.name = name;
        this.age = age;
    }
  
    // Getters and Setters
    public String getName() { return name; }
  
    public void setName(String name) { this.name = name; }
  
    private int getAge() { return age; }
  
    public void setAge(int age) { this.age = age; }
  
    // Override to string method to get
    // Required output when called
    @Override public String toString()
    {
        return "Employee [name=" + name + ", age=" + age
            + "]";
    }
}
  
class GFG {
  
    public static void main(String[] args)
    {
        try {
            // Student class object
            Student e = new Student("Kapil", 23);
  
            // Create Method object
            Method privateMethod
                = Student.class.getDeclaredMethod("getAge");
  
            // Set the accessibility as true
            privateMethod.setAccessible(true);
  
            // Store the returned value of
            // private methods in variable
            int age = (int)privateMethod.invoke(e);
            System.out.println("Age of Student: " + age);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

输出:

Age of Student: 23