how to read object attribute dynamically in java?

后端 未结 5 1246
清歌不尽
清歌不尽 2021-02-07 12:38

Is there any way to read and print the object attribute dynamically(Java) ? for example if I have following object

public class A{
  int age ;
  String name;
           


        
5条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-07 12:47

    You can use reflection, but the API is not very nice to use. But what you are trying to do is not at all object-oriented. The A and B should have method "print yourself" which would output their values (you should specify the method in superclass/interface to call the method using polymorphism).

提交回复
热议问题