13

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?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
P45 Imminent
  • 8,319
  • 4
  • 35
  • 78

3 Answers3

24

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
Peter Walser
  • 15,208
  • 4
  • 51
  • 78
5
Modifier.isFinal(clz.getModifiers())
niiraj874u
  • 2,180
  • 1
  • 12
  • 19
2

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

if (Modifier.isFinal(clz.getModifiers())
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194