gauri
gauri

Reputation: 231

how to obtain list of fields in class in java?

I want to retrieve list of member variables of a specified class along with other information like datatype, size, value,etc. This is possible using Reflection class. But is there any way other than Reflection class to get this information? Thanks in advance.

Upvotes: 2

Views: 190

Answers (6)

zubrabubra
zubrabubra

Reputation: 514

  1. reflection, this is actually easiest way to do that
  2. parsing source code using generated compiler (antlr project has java grammar file), it's a little bit more complicated and will require additional dependencies in your project, this is suitable only in case you have source code
  3. reading java class file and analyzing it, the most complicated. you'll have to create a java bytecode parser to read binary file. But this could be the fastest way (no additional deps LALR-k parsing, no overhead like in reflection), you'll be in control what to read, how to read, could work with compiled java code.

The question is why do you think reflection is not suitable for you? It made much faster in java 1.5 comparing to previous java releases.

Upvotes: 1

Thresh
Thresh

Reputation: 943

Apache commons-lang package has a very useful tool: ReflectionToStringBuilder. Here is the link to javadoc: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/builder/ReflectionToStringBuilder.html

Upvotes: 0

Giann
Giann

Reputation: 3192

Just use the methods provided by the field class of your class. See object Class.

Upvotes: 1

Koenighotze
Koenighotze

Reputation: 41

The org.springframework.util.ReflectionUtils class is actually quite the helper in these cases.

Upvotes: 0

Jigar Joshi
Jigar Joshi

Reputation: 240996

Yes introspection may help you apart from Reflection

Upvotes: 1

Riduidel
Riduidel

Reputation: 22308

The only other way I'm aware of is via source-code analysis, with tools like Spoon.

Upvotes: 1

Related Questions