Java Modifiers Example

0

If a class is not accessible and we want to create an instance reflectively, we can change the accessibility of the reflected object, constructor object in this case, so that the Java language access check is suppressed when it is used. We can differentiate whether a class is accessible by their modifiers. At times we also validate whether a method is final or static. Suppose the framework relies on a proxy object which intercepts and overrides a method, we must validate that none of the methods declared are final. In this article, we will see how to make use of Java Modifiers.

Java Modifier API

Java supports the below modifiers:

  1. public
  2. protected
  3. private
  4. static
  5. final
  6. native
  7. volatile
  8. abstract
  9. synchronized
  10. strictfp
  11. transient

You can access the modifiers using getModifiers() which returns an int which acts as a bit vector. In order to identify the individual modifier from the returned bit vector, Java reflection API provides a convenience class called Modifier which helps to decode the return value of getModifiers().

Class Modifiers

In the below example, we identify whether a class defined is public, private or protected. We also check whether a class is static.
We use the convenience methods offered by Modifier. We pass in the class modifiers which we get using Class.getModifiers()

  1. Modifier.isPublic() – True if the public modifier is present in the set of class modifiers.
  2. Modifier.isPrivate() – True if the private modifier is present in the set of class modifiers.
  3. Modifier.isProtected() – True if the protected modifier is present in the set of class modifiers.
  4. Modifier.isStatic() – True if the static modifier is present in the set of class modifiers.

ClassModifiersExample:

package com.javarticles.reflection;

import java.lang.reflect.Modifier;

public class ClassModifiersExample {
    public static void main(String[] args) throws Exception {
        printClassModifiers();;
    }

    private static class InnerPrivateStaticClass {
    }

    protected static class InnerProtectedStaticClass {
    }
    
    static class InnerStaticClass {
    }

    interface InnerInterface {
        
    }
    
    private static void printClassModifiers() {
        System.out.println("Is ClassModifiersExample public? "
                + Modifier.isPublic(ClassModifiersExample.class
                        .getModifiers()));
        System.out.println("Is InnerPrivateStaticClass private? "
                + Modifier.isPrivate(InnerPrivateStaticClass.class
                        .getModifiers()));
        System.out.println("Is InnerProtectedStaticClass protected? "
                + Modifier.isProtected(InnerProtectedStaticClass.class
                        .getModifiers()));
        System.out.println("Is InnerStaticClass static? "
                + Modifier.isStatic(InnerStaticClass.class
                        .getModifiers()));
        System.out.println("Is InnerInterface an interface?" + Modifier.isInterface(InnerInterface.class.getModifiers()));
    }    
}

Output:

Is ClassModifiersExample public? true
Is InnerPrivateStaticClass private? true
Is InnerProtectedStaticClass protected? true
Is InnerStaticClass static? true
Is InnerInterface an interface?true

Method Modifiers

In the below example, we examine the class methods and print the ones which are static or final. We get all the method objects using Class.getDeclaredMethods() and the method modifiers using Method.getModifiers().

MethodModifiersExample:

package com.javarticles.reflection;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class MethodModifiersExample {
    public static void main(String[] args) throws Exception {
        printStaticFinalMembers();        
    }

    public String getInstanceName() {
        return "Instance Name";
    }
    
    public final String finalMethod() {
        return "Final Method";
    }

    public static String getStaticName() {
        return "Static Name";
    }
    
    private static void printStaticFinalMembers() {
        Method[] methods = MethodModifiersExample.class.getDeclaredMethods();
        for (Method method : methods) {
            if (Modifier.isStatic(method.getModifiers())) {
                System.out.println("Static method: " + method.getName());
            }
            if (Modifier.isFinal(method.getModifiers())) {
                System.out.println("Final method: " + method.getName());
            }
        }
    }
}

Output:

Static method: main
Static method: printStaticFinalMembers
Final method: finalMethod
Static method: getStaticName

Constructor Modifiers

You want to create an instance of a class which is not accessible. You need first make sure that the class or the constructor itself is not accessible.

  1. Modifier.isPublic(ctor.getModifiers() – Checks whether constructor is not public
  2. Modifier.isPublic(ctor.getDeclaringClass().getModifiers()) – Whether the class itself is not public
  3. Constructor.isAccessible() – Whether the constructor is accessible

You make the constructor accessible using:

Constructor.setAccessible(true);
    private static void makeAccessible(Constructor<?> ctor) {
        if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor
                .getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
            ctor.setAccessible(true);
        }
    }

PackageScopedTestBean:

package com.javarticles.reflection.packageA;

class PackageScopedTestBean {
}

ConstructorModifiersExample:

package com.javarticles.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;

public class ConstructorModifiersExample {
    public static void main(String[] args) throws Exception {
        createPackageClassInstance();
    }

    private static void createPackageClassInstance() throws Exception {
        Class<?> testBean = Class
                .forName("com.javarticles.reflection.packageA.ProtectedTestBean");
        Constructor<?> protectedConstructor = testBean
                .getDeclaredConstructor((Class[]) null);
        makeAccessible(protectedConstructor);
        
        Object o = protectedConstructor.newInstance();
        System.out.println("ProtectedTestBean object: " + o);
    }

    private static void makeAccessible(Constructor<?> ctor) {
        if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor
                .getDeclaringClass().getModifiers())) && !ctor.isAccessible()) {
            ctor.setAccessible(true);
        }
    }
}

If it is not made accessible programatically, you will get java.lang.IllegalAccessException error:

Exception in thread "main" java.lang.IllegalAccessException: Class com.javarticles.reflection.ConstructorModifiersExample can not access a member of class
com.javarticles.reflection.packageA.PackageScopedTestBean with modifiers ""

Output:

PackageScopedTestBean object: [email protected]42

Download the source code

This was an example about Java Modifiers at class, method and constructor level.

You can download the source here: javaModifiersExample.zip
Share.

Comments are closed.