For example, there is a code:

class B { private int i = 22; } class A { // тут код который выводит переменную i } 

Condition: Class B cannot be changed. class A can be changed (ie, inherit class B, etc.)

  • Describe why you so pervert? - jmu
  • Here another question (fundamental) arises. - Why are there such strictness with encapsulation? Who needs to get around, still get around. Only the program becomes more incomprehensible. - avp
  • Did not quite understand what you meant, "Who should get around, still get around"? Using reflection is not considered a burglary, just look at the source of the package: it allows you to do everything except that it is forbidden (for any such action, java checks permissions). By default, everything is allowed - so these "Kulhak" work. In the applets, on the contrary, much is forbidden. Neither work with private files, nor work with a local network. To start this work, you need to set permissions separately (in both cases). Or did you mean hacking with JVM memory editing? - jmu
  • I mean, it’s impossible to use reflection if permissions are configured for the application. - jmu
  • Absolutely not meant any hacking or malicious use. This is about the convenience of using the code (libraries), which generally (if desired) can be changed (by the programmer calling it) at the source level. I do not know that Java (and other programming systems familiar to me) really does not provide convenient access to the interiors of objects. - avp

2 answers 2

Through Reflection

  B b = new B(); Class clazz = B.class; Field iField = clazz.getDeclaredField("i"); iField.setAccessible(true); int fieldValue = iField.getInt(b); System.out.println("i = " + fieldValue); 
  • and if class B is abstract and its instance is not obtained, how can a thread be? - Yura Ivanov
  • Through an instance of a class that is inherited from asbestos, not? No specific instance - no data in the object - no value can be obtained. You can probably pervert and dynamically create a class inherited from the abstract, then create an instance ... - bald2b
  • Sorry, replace Field iField = B.class.getDeclaredField ("i"); on Class clazz = B.class; Field iField = clazz.getDeclaredField ("i"); - bald2b
  • Yes, thank you. I have already fixed it - serhio28
  • and besides reflection there is no other way? maybe through serialization? (I understand this a little and therefore I ask) - Viacheslav

I think it's easier to add a method to class A.

 public int getI(){ return i; } 

the so-called getter .

  • Read the question. Condition: Class B cannot be changed. With this condition, the only option is reflection. - ReinRaus