0%

Java反射机里Field的getModifiers()

1. modifiers列表

public: 1
private: 2
protected: 4
static: 8
final: 16
synchronized: 32
volatile: 64
transient: 128
native: 256
interface: 512
abstract: 1024
strict: 2048

  • Java反射机制中,Field的getModifiers()方法返回类型为int类型;值表示该字段的修饰符, 见上面映射关系。

  • 如果多个修饰符, modifiers的值是他们所有单个int值的加和.
    如 modifiers=25 -> public+static+final=25
    public static final int score = 2;

2. 代码示例

Talk is cheap , show me the code:

import lombok.extern.slf4j.Slf4j;

/**
 * @author weijun.nie
 * @date 2020-04-17 23:18
 */
@Slf4j
public class FieldModifiersTest {
    public static final int score = 2;
    public static volatile int count = 0;

    public static void main(String[] args) {

        Class clazz = FieldModifiersTest.class;
        try {
            int modifiersScore = clazz.getField("score").getModifiers();
            int modifiersCount = clazz.getField("count").getModifiers();
            
            // modifiersScore = 25 (public+static+final)
            log.info("modifiersScore = {}", modifiersScore);
            
            // modifiersScore = 11001
            log.info("modifiersScore = {}", Integer.toBinaryString(modifiersScore));

            log.info("--------------------------------");
           
           // modifiersCount = 73 (public+static+volatile)
            log.info("modifiersCount = {}", modifiersCount);
            
            // modifiersScore = 1001001
            log.info("modifiersCount = {}", Integer.toBinaryString(modifiersCount));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

[注:] @Slf4j 是lombok的注解, 方便打印日志, 没用过的可以替换为System.out.println理解.