Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell using reflection if a class is final

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?

like image 601
P45 Imminent Avatar asked Apr 25 '14 10:04

P45 Imminent


People also ask

How do you find the class of a reflection?

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");

What happens if we define class final?

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.

What does class reflection mean?

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.


1 Answers

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
like image 111
Peter Walser Avatar answered Sep 19 '22 04:09

Peter Walser