Reputation: 7370
I want to write a java program to print all (public or private) parameters of a class and their types. I think I have to use reflection, but I'm noob at java reflection.
As an example, I need the my program to run on below class and result in following output:
class a{
public int b;
public int c;
private String s;
}
output:
b: int
c: int
s: St
Finally my question is how to get a list of parameters of a class and their types.
Upvotes: 0
Views: 90
Reputation: 55213
I would recommend you explore the javadoc, starting with the Class
class:
Instances of the class
Class
represent classes and interfaces in a running Java application.
Of note is the method getDeclaredFields()
, which returns an array of Field
objects representing the fields the class declares.
Also take note of the ways to obtain a Class
object:
Class<MyClass> c = MyClass.class; //statically
MyClass mc = new MyClass();
Class<? extends MyClass> c2 = mc.getClass(); //dynamically
Upvotes: 6
Reputation: 93030
try {
Class c = Class.forName("a");
Field[] fs = c.getDeclaredFields();
for(Field f : fs){
System.out.println(f.getName()+": "+f.getType().getSimpleName());
}
} catch (ClassNotFoundException e) {}
Upvotes: 3