Suppose I have a class:
public final class Foo
and a reflected Class clz
reference that refers to that class.
How can I tell (using clz
) that Foo
is final
?
In order to reflect a Java class, we first need to create an object of Class . And, using the object we can call various methods to get information about methods, fields, and constructors present in a class. class Dog {...} // create object of Class // to reflect the Dog class Class a = Class. forName("Dog");
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class. You cannot extend a final class.
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
Using Class#getModifiers
:
Modifier.isFinal(clz.getModifiers())
The modifiers of a class (or field, or method) are represented as a packed-bit int
in the reflection API. Each possible modifier has its own bit mask, and the Modifier
class helps in masking out those bits.
You can check for the following modfiers:
abstract
final
interface
native
private
protected
public
static
strictfp
synchronized
transient
volatile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With