Skip to main content

Java : How to check if the field of a class is FINAL by Reflection

Points To Remember


  • You can use Reflection to check if the field of a class is final or not.
  • You need to get the modifiers of the field to check if the field is final

How to check if the field of a class is final by Reflection

The following is the only way to check if the field is final or not

field.getModifiers()& Modifier.FINAL) == Modifier.FINAL 

Following program shows how to get the final fields from a class.

package com.ekiras.demo;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class Test {

public static void main(String args[]){
Field[] fields = Person.class.getDeclaredFields();
for(Field field : fields){
if((field.getModifiers()& Modifier.FINAL) == Modifier.FINAL ){
System.out.println("final field :: " + field.getName());
}
}
}
}

class Person{
public static final int someConstant = 2;
private String name;
private String email;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}




}



Comments