How to Find Class Fields with Specified Data Type in Java


In this example we will show how to find class fields with specified data type in Java.

Source Code

(1)Person.java

package com.beginner.examples;

public class Person {
     String name;
     int age;
     boolean sex;
}

(2)FindClassFields.java

package com.beginner.examples;

import java.lang.reflect.Field;

public class FindClassFields {

	public static void main(String[] args) {
		
		Field[] fields = Person.class.getDeclaredFields();
		
		for(Field field : fields) {
			System.out.println("field name is " + field.getName() + ", "+ "field type is " + field.getType());
		}

	}

}

Output:

field name is name, field type is class java.lang.String
field name is age, field type is int
field name is sex, field type is boolean

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments