P45 Imminent
P45 Imminent

Reputation: 8591

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?

Upvotes: 13

Views: 2664

Answers (3)

Peter Walser
Peter Walser

Reputation: 15706

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

Upvotes: 24

Niraj Patel
Niraj Patel

Reputation: 2208

Modifier.isFinal(clz.getModifiers())

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500675

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

if (Modifier.isFinal(clz.getModifiers())

Upvotes: 2

Related Questions