Checking the specified class contains a field matching the specified name using Java Reflections
Overview
In this tutorial we check if the specified field exists for a class. We make use of Java Reflections.Lets Begin
Initially using Java Reflections the class fields are looped and stored in a HashSet. Then later if it is to be checked if a field exists for the class it is checked if it is present in the properties Set created before. Create the Employee class as follows-package com.javainuse.domain; public class Institute { private String name; private int code; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }
package com.javainuse.main; import java.lang.reflect.Field; import java.util.HashSet; import java.util.Set; import com.javainuse.domain.Institute; public class CheckFieldMain { public static void main(String[] args) { Institute institute = new Institute(); Set<String> sourceFieldList = getAllFields(institute.getClass()); boolean hasName = ifPropertpresent(sourceFieldList, "name"); System.out.println(hasName); boolean hasAddress = ifPropertpresent(sourceFieldList, "address"); System.out.println(hasAddress); } /** * Check if field is present for the class * @param properties * @param propertyName * @return */ private static boolean ifPropertpresent(final Set<String> properties, final String propertyName) { if (properties.contains(propertyName)) { return true; } return false; } /** * Recursive method to get fields * * @param type * @return */ private static Set<String> getAllFields(final Class<?> type) { Set<String> fields = new HashSet<String>(); //loop the fields using Java Reflections for (Field field : type.getDeclaredFields()) { fields.add(field.getName()); } //recursive call to getAllFields if (type.getSuperclass() != null) { fields.addAll(getAllFields(type.getSuperclass())); } return fields; } }
Download Source Code
Download it - Java project to check if field is present in classSee Also
Understand Java 8 Method References using Simple Example Java - PermGen space vs MetaSpace Java 8 Lambda Expression- Hello World Example Java 8 Features Java Miscelleneous Topics Java Basic Topics Java- Main Menu