how to read object attribute dynamically in java?

后端 未结 5 1182
清歌不尽
清歌不尽 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 13:11

    I think I would consider a different approach.

    If you really want to treat these like data is there any reason they couldn't be hashtables (Do they have associated code)?

    Reflection will do it but it's a last resort--you should always seriously consider different approaches before dropping to reflection.

    Cases where you must access variables like that exist--like database mapping (Hibernate) and injection (Spring). You might want to consider if a packaged solution like that fits your need so that future programmers can understand what you did without learning everything about your specific solution.

    Also, Spring injection can do things that might fit your needs.

    Also also if you are going to use reflection, seriously consider annotations so that you aren't tying your functionality to what should be simple arbitrary attribute names.

提交回复
热议问题