Points To Remember
- You can use Reflection to check if the field of a class is static or not.
- You need to get the modifiers of the field to check if the field is static.
How to check if the field of a class is static by Reflection
The following is the only way to check if the field is static or notfield.getModifiers()& Modifier.STATIC) == Modifier.STATIC
Following program shows how to get the static 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.STATIC) == Modifier.STATIC ){
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
Post a Comment