How can I loop over a class attributes in java dynamically.
For eg :
public class MyClass{
private type1 att1;
private type2 att2;
...
public void function(){
for(var in MyClass.Attributes){
System.out.println(var.class);
}
}
}
is this possible in Java?
There is no linguistic support to do what you’re asking for.
You can reflectively access the members of a type at run-time using reflection (e.g. with
Class.getDeclaredFields()to get an array ofField), but depending on what you’re trying to do, this may not be the best solution.See also
Related questions
Example
Here’s a simple example to show only some of what reflection is capable of doing.
The above snippet uses reflection to inspect all the declared fields of
class String; it produces the following output:Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection
These are excerpts from the book: