Java – find class fields with specified data type - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
find class fields with specified data type

Java – find class fields with specified data type

Display all fields and data type

A Java reflection example to loop over all the fields declared by a class.
1.1 A POJO.
CompanyA.java
package com.mycareerrepublic.test;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class CompanyA {

String orgName;
int count;
List<String> comments;
Set<String> branches;
Map<String, String> extra;

//...
}
1.2 Use Java reflection APIs getDeclaredFields() to loop over and display the field name and data type.
Test.java
package com.mycareerrepublic.test;

import java.lang.reflect.Field;
import java.util.List;

public class Test {

public static void main(String[] args) {

Field[] fields = CompanyA.class.getDeclaredFields();
for(Field f : fields){
Class t = f.getType();
System.out.println("field name : " + f.getName() + " , type : " + t);
}

}

}
Output
field name : orgName , type :class java.lang.String
field name : count , type :int
field name : comments , type :interface java.util.List
field name : branches , type :interface java.util.Set
field name : extra , type :interface java.util.Map

2. Find class fields with specified data type

2.1 This example will find all fields with List data type.
Test.java
package com.mycareerrepublic.test;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class TestAbc {

public static void main(String[] args) {

List<String> list = getFieldNameWithListDataType();
for(String data : list){
System.out.println("List : " + data);
}


}

private static List<String> getFieldNameWithListDataType(){

List<String> result = new ArrayList<>();

//CompanyA, refer 1.1
Field[] fields = CompanyA.class.getDeclaredFields();
for(Field f : fields){

// use equals to compare the data type.
if(f.getType().equals(List.class)){
result.add(f.getName());
}

//for other data type

//Map
//if(f.getType().equals(Map.class))

//Set
//if(f.getType().equals(Set.class))

//primitive int
//if(f.getType().equals(int.class))
//if(f.getType().equals(Integer.TYPE))

//primitive long
//if(f.getType().equals(long.class))
//if(f.getType().equals(Long.TYPE))

}

return result;

}

}
Output
comments
Note
For primitive types like int, you can compare with int.class or Integer.TYPE

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.