杰瑞科技汇

Java getModifiers()方法返回值具体含义是什么?

Of course! In Java, getModifiers() is a method from the java.lang.reflect package, primarily used with Class, Constructor, Field, and Method objects. It returns an integer that represents the access modifiers (like public, private) and other modifiers (like static, final) of a language element.

Java getModifiers()方法返回值具体含义是什么?-图1
(图片来源网络,侵删)

Here’s a detailed breakdown of how it works and how to use it.


The Core Concept: Bitwise Flags

The key to understanding getModifiers() is that it doesn't return a string or an enum. It returns an int where each bit in the integer represents a specific modifier.

  • Bitwise Representation: Java uses predefined constants in the java.lang.reflect.Modifier class. Each constant has a unique binary representation (a single bit set to 1).
  • Combining Modifiers: If a class or method has multiple modifiers, their corresponding bit flags are combined using a bitwise OR () operation. This is how multiple states can be stored in a single integer.

Example: The public static final int MY_CONSTANT = 10;

  • public is 0x00000001 (or 1)
  • static is 0x00000008 (or 8)
  • final is 0x00000010 (or 16)

The integer returned by getModifiers() for this field would be 1 | 8 | 16 = 25.

Java getModifiers()方法返回值具体含义是什么?-图2
(图片来源网络,侵删)

The Modifier Helper Class

You should almost never inspect the bits of the integer directly. The java.lang.reflect.Modifier class provides static utility methods to check for specific modifiers in a clean, readable way.

The most important method is isModifier(int mod, int modMask).

  • mod: The integer returned by your getModifiers() call.
  • modMask: The constant you want to check for (e.g., Modifier.PUBLIC).

The method performs a bitwise AND (&) operation. If the result is non-zero, it means the bit for that modifier was set.

How it works internally: (mod & modMask) != 0

Java getModifiers()方法返回值具体含义是什么?-图3
(图片来源网络,侵删)

How to Use getModifiers(): A Step-by-Step Guide

Let's use a sample class and then reflect on it.

Sample Class: Sample.java

package com.example.reflect;
import java.util.List;
// A class with various modifiers
public final class Sample {
    // A public static final field
    public static final int MAX_SIZE = 100;
    // A private constructor
    private Sample() {}
    // A public instance method
    public void doSomething() {
        System.out.println("Doing something...");
    }
    // A protected static method
    protected static void doSomethingStatic() {
        System.out.println("Doing something static...");
    }
}

Java Code to Inspect Modifiers

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class InspectModifiers {
    public static void main(String[] args) throws ClassNotFoundException {
        // 1. Get the Class object for our Sample class
        Class<?> clazz = Class.forName("com.example.reflect.Sample");
        // --- Inspecting Class Modifiers ---
        System.out.println("--- Inspecting Class: " + clazz.getName() + " ---");
        int classModifiers = clazz.getModifiers();
        System.out.println("Raw Modifier Int: " + classModifiers);
        System.out.println("Is Public? " + Modifier.isPublic(classModifiers));
        System.out.println("Is Final? " + Modifier.isFinal(classModifiers));
        System.out.println("Is Interface? " + Modifier.isInterface(classModifiers));
        System.out.println("Is Abstract? " + Modifier.isAbstract(classModifiers));
        System.out.println(); // Newline
        // --- Inspecting Field Modifiers ---
        try {
            Field maxsizeField = clazz.getField("MAX_SIZE");
            System.out.println("--- Inspecting Field: " + maxsizeField.getName() + " ---");
            int fieldModifiers = maxsizeField.getModifiers();
            System.out.println("Is Public? " + Modifier.isPublic(fieldModifiers));
            System.out.println("Is Static? " + Modifier.isStatic(fieldModifiers));
            System.out.println("Is Final? " + Modifier.isFinal(fieldModifiers));
            System.out.println(); // Newline
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        // --- Inspecting Method Modifiers ---
        try {
            Method doSomethingMethod = clazz.getMethod("doSomething");
            System.out.println("--- Inspecting Method: " + doSomethingMethod.getName() + " ---");
            int methodModifiers = doSomethingMethod.getModifiers();
            System.out.println("Is Public? " + Modifier.isPublic(methodModifiers));
            System.out.println("Is Static? " + Modifier.isStatic(methodModifiers));
            System.out.println("Is Synchronized? " + Modifier.isSynchronized(methodModifiers));
            System.out.println(); // Newline
            Method doSomethingStaticMethod = clazz.getDeclaredMethod("doSomethingStatic");
            System.out.println("--- Inspecting Method: " + doSomethingStaticMethod.getName() + " ---");
            int staticMethodModifiers = doSomethingStaticMethod.getModifiers();
            System.out.println("Is Protected? " + Modifier.isProtected(staticMethodModifiers));
            System.out.println("Is Static? " + Modifier.isStatic(staticMethodModifiers));
            System.out.println(); // Newline
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        // --- Inspecting Constructor Modifiers ---
        try {
            Constructor<?> constructor = clazz.getDeclaredConstructor();
            System.out.println("--- Inspecting Constructor: " + constructor.getName() + " ---");
            int constructorModifiers = constructor.getModifiers();
            System.out.println("Is Private? " + Modifier.isPrivate(constructorModifiers));
            System.out.println("Is Public? " + Modifier.isPublic(constructorModifiers));
            System.out.println(); // Newline
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

Output of the Code

--- Inspecting Class: com.example.reflect.Sample ---
Raw Modifier Int: 17
Is Public? true
Is Final? true
Is Interface? false
Is Abstract? false
--- Inspecting Field: MAX_SIZE ---
Is Public? true
Is Static? true
Is Final? true
--- Inspecting Method: doSomething ---
Is Public? true
Is Static? false
Is Synchronized? false
--- Inspecting Method: doSomethingStatic ---
Is Protected? true
Is Static? true
--- Inspecting Constructor: com.example.reflect.Sample ---
Is Private? true
Is Public? false

Commonly Used Modifier Constants

Here is a list of the most common constants you'll use:

Modifier Type Constant (from Modifier class) Description
Access Modifiers public Declared public.
private Declared private.
protected Declared protected.
package-private Not a constant! Check with !Modifier.isPublic() && !Modifier.isPrivate() && !Modifier.isProtected().
Class/Interface final Cannot be subclassed.
abstract Cannot be instantiated.
strictfp Uses strict floating-point mode.
Member (Field/Method) static Belongs to the class, not an instance.
final Cannot be changed (fields) or overridden (methods).
synchronized The method is synchronized.
volatile The field is volatile.
transient The field is transient and will not be serialized.
native The method is implemented in a platform-dependent language like C.
Annotation @interface Not a constant! Check with clazz.isAnnotation().
Enum enum Not a constant! Check with clazz.isEnum().

Important Considerations

  1. getModifiers() vs. getDeclaredModifiers()

    • getModifiers(): Returns the modifiers for the public member (field, method, constructor) inherited from a public superclass or interface. If no such public member exists, it throws a NoSuchFieldException or NoSuchMethodException.
    • getDeclaredModifiers(): Returns the modifiers for the member declared directly in the class, ignoring any inherited members. This is often more useful because it doesn't fail on inherited members.
  2. Access Control

    • Standard reflection respects Java's access control. You cannot get a Method object for a private method using getMethod(). You must use getDeclaredMethod().
    • Even with getDeclaredMethod(), you cannot normally invoke a private method. To bypass this, you need to call setAccessible(true) on the Method object, which requires the ReflectPermission suppressAccessChecks.
  3. Modifier.toString(int mod)

    • If you ever need the modifier names as a String (e.g., for logging), the Modifier class provides a handy toString(int mod) method.
      int modifiers = clazz.getModifiers();
      String modifierString = Modifier.toString(modifiers); // Returns "public final"
      System.out.println("Class modifiers as string: " + modifierString);
分享:
扫描分享到社交APP
上一篇
下一篇