Get Modifiers of an Object using Reflection

This example demonstrates how to get the modifiers used in a class using the reflection API. One can use the getModifiers() method in the Class object to know about each modifier used in that specific class. Call isAbstract(int mod), isFinal(int mod), isInterface(int mod), isNative(int mod), isPrivate(int mod), isProtected(int mod), isPublic(int mod) and isStatic(int mod) methods to know about each modifier.

Lets look at the example below to print the modifiers used in java.lang.Math class.


import java.lang.reflect.Modifier;

 * Get Modifiers of a class using Reflection API
 * @author krishna
public class JavaBeatReflectionExample {
	public static void main(String[] args) throws Exception {
		Class<?> clazz = java.lang.Math.class;
		// return the modifiers for this class or interface encoded in an integer
		int mod = clazz.getModifiers();
		System.out.println("Interface Modifier: " + Modifier.isInterface(mod));
		System.out.println("Static Modifier: " + Modifier.isStatic(mod));
		System.out.println("Abstract Modifier: " + Modifier.isAbstract(mod));
		System.out.println("Final Modifier: " + Modifier.isFinal(mod));
		System.out.println("Native Modifier: " + Modifier.isNative(mod));
		System.out.println("Private Modifier: " + Modifier.isPrivate(mod));
		System.out.println("Protected Modifier: " + Modifier.isProtected(mod));
		System.out.println("Public Modifier: " + Modifier.isPublic(mod));



Interface Modifier: false
Static Modifier: false
Abstract Modifier: false
Final Modifier: true
Native Modifier: false
Private Modifier: false
Protected Modifier: false
Public Modifier: true



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind