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

前端 未结 14 1690
梦毁少年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 11:52

    Try to go around the problem for the case, the calass of which you want to set/get data is one of your own classes.

    Just create a public setter(Field f, Object value) and public Object getter(Field f) for that. You can even do some securoty check on your own inside theses member functions. E.g. for the setter:

    class myClassName {
        private String aString;
    
        public set(Field field, Object value) {
            // (A) do some checkings here  for security
    
            // (B) set the value
            field.set(this, value);
        }
    }
    

    Of course, now you have to find out the java.lang.reflect.Field for sString prior to setting of field value.

    I do use this technique in a generic ResultSet-to-and-from-model-mapper.

提交回复
热议问题