reflection
Get Modifiers from an Object
In this example we shall show you how to get the modifiers of a class. To get the modifiers of a class one should perform the following steps:
- Call
getModifiers()
API method of Class to get the Java language modifiers for this class or interface, encoded in an integer. The modifiers consist of the Java Virtual Machine’s constants for public, protected, private, final, static, abstract and interface; they should be decoded using the methods of class Modifier. - Call
isAbstract(int mod)
,isFinal(int mod)
,isInterface(int mod)
,isNative(int mod)
,isPrivate(int mod)
,isProtected(int mod)
,isPublic(int mod)
andisStatic(int mod)
API methods of Modifier to get true if the integer argument includes the one of the specified modifiers, else false,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.lang.reflect.Modifier; public class GetModifiersFromAnObject { public static void main(String[] args) { Class<?> clazz = java.lang.ThreadLocal.class; // return the modifiers for this class or interface encoded in an integer int mod = clazz.getModifiers(); System.out.println("Abstract: " + Modifier.isAbstract(mod)); System.out.println("Final: " + Modifier.isFinal(mod)); System.out.println("Interface: " + Modifier.isInterface(mod)); System.out.println("Native: " + Modifier.isNative(mod)); System.out.println("Private: " + Modifier.isPrivate(mod)); System.out.println("Protected: " + Modifier.isProtected(mod)); System.out.println("Public: " + Modifier.isPublic(mod)); System.out.println("Static: " + Modifier.isStatic(mod)); } }
Output:
Abstract: false
Final: false
Interface: false
Native: false
Private: false
Protected: false
Public: true
Static: false
This was an example of how to get the modifiers of a class in Java.