How to check if a Java object is final
final modifier can be applied at class level. If a Class is marked final it cannot be extended.
Sample final Class
final class MyCustomClass {
}
Using java.lang.reflect.Modifier
Using java.lang.reflect.Modifier,, We can check if a class is final though java.lang.reflect.Modifier.isFinal() method.
MyCustomClass.class.getModifiers() will provide an integer number representing the class modifier. For example for the above class it prints 16.
Now the value returned from the getModifiers() can be decoded with method Modifier.isFinal();
JavaReflectionModifiers
import java.lang.reflect.Modifier;
public class JavaReflectionModifiers {
public static void main(String[] args) {
//prints 16
System.out.println(MyCustomClass.class.getModifiers());
//returns true
Modifier.isFinal(MyCustomClass.class.getModifiers());
}
}
final class MyCustomClass {
}
More Examples
Examples
package Java14;
import java.lang.reflect.Modifier;
public class JavaReflectionModifiers {
public static void main(String[] args) {
System.out.println(MyCustomClass.class.getModifiers());
//prints true
System.out.println(Modifier.isFinal(MyCustomClass.class.getModifiers()));
//prints true
System.out.println(Modifier.isFinal(String.class.getModifiers()));
//prints false
System.out.println(Modifier.isFinal(Number.class.getModifiers()));
}
}
final class MyCustomClass {
}
No comments :
Post a Comment
Please leave your message queries or suggetions.