JAVA判断修饰符的方法(比如static,final)

2014-11-24 03:24:30 · 作者: · 浏览: 0

留笔备忘...
虽然有时会用到,每次都忘记是哪个函数了...汗
直接上代码:

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


public class Test {
abstract class FieldTest {
private String str;
private static final int CONSTANTS = 1;

public abstract void test();
}

public static void main(String[] args) {
Field[] fields = FieldTest.class.getDeclaredFields();

for(Field field : fields) {
System.out.println(field.getName() + " -> static:" + Modifier.isStatic(field.getModifiers()) + " final:" + Modifier.isFinal(field.getModifiers()));
}

Method[] methods = FieldTest.class.getDeclaredMethods();

for(Method method : methods) {
System.out.println(method.getName() + " -> abstract:" + Modifier.isAbstract(method.getModifiers()));
}
}
}

主要就是 Modifier.isXXXX()函数及field/method .getModifiers()函数就可以判断类/接口/字段/方法的修饰符

贴部分Modifer类的定义:

/**
* The int value representing the public
* modifier.
*/
public static final int PUBLIC = 0x00000001;

/**
* The int value representing the private
* modifier.
*/
public static final int PRIVATE = 0x00000002;

/**
* The int value representing the protected
* modifier.
*/
public static final int PROTECTED = 0x00000004;

/**
* The int value representing the static
* modifier.
*/
public static final int STATIC = 0x00000008;

......

其中的判断函数:

public static boolean isStatic(int mod) {
return (mod & STATIC) != 0;
}

摘自 SoL 学习无止境