简体   繁体   中英

How can I make an object of class having private fields and constructor using reflection?

Let's say I have the following class

 class Person
 {
     private double salary;
     private Foo(double x, double y)
     {
         salary = x;
     }         
 }

How would I create an instance of a class Person from outside and access its salary field using reflection?

Use Field.setAccessible(true) first if you're accessing it from a different class.

import java.lang.reflect.*;

class SomeObject{
    private String string;

    void setString(String value){
        string= value;
    }
}

class TestPrivateAccess{
    public static void main(String[] args) throws Exception{
        SomeObject ojb = new SomeObject();
        obj.setString("astring");

        Field field = SomeObject.class.getDeclaredField("string");
        field.setAccessible(true);
        Object value = field.get(obj);
        System.out.println(value);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM