How to get all Declared Fields in a Class
Points To Remember
- We can use reflection to find all the fields available within a class.
- We can get all the declared fields in a class by getDeclaredFields().
- We can search for any field in a class by using getField(). It throws NoSuchFieldException if the field does not exist in the class.
Program : Get all the declared fields in a class
import java.lang.reflect.Field; class SampleClass{ String s1 = "Class variable"; int a = 123; } class Test{ public static void main(String args[]){ Test obj = new Test(); try{ Class clazz = Class.forName("SampleClass"); Field feilds[] = obj.getDeclaredFields(clazz); for(Field feild : feilds){ System.out.println(feild); } }catch(Exception e){ e.printStackTrace(); } } public Field[] getDeclaredFields(Class clazz){ return clazz.getDeclaredFields(); } }
java.lang.String SampleClass.s1 int SampleClass.a
Program : Get a particular field declared in a class.
import java.lang.reflect.Field; class SuperClass{ public String abc = "super class"; } class SampleClass extends SuperClass{ public String s1 = "Class variable"; public int a = 123; } class Test{ public static void main(String args[]){ Test obj = new Test(); try{ Class clazz = Class.forName("SampleClass"); Field feild = obj.getField(clazz, "abc"); System.out.println(feild); }catch(Exception e){ e.printStackTrace(); } } public Field getField(Class clazz, String field) throws NoSuchFieldException{ return clazz.getField(field); } }
public java.lang.String SuperClass.abcWe can only get the public fields declared in a class using this method. In case we try to access the private or default fields of the class, we will get a NoSuchFieldException.
No comments: