Home » Core Java » reflection » Get Modifiers from an Object

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

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) and isStatic(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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of