Question

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?

Was it helpful?

Solution

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

OTHER TIPS

Modifier.isFinal(clz.getModifiers())

You use Class.getModifiers(), ideally using the Modifier class to interpret the return value in a readable way:

if (Modifier.isFinal(clz.getModifiers())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top