首页 > 代码库 > Spring 反射工具类ReflectionUtils

Spring 反射工具类ReflectionUtils

    public static final int PUBLIC           = 0x00000001;

   
    public static final int PRIVATE          = 0x00000002;

 
    public static final int PROTECTED        = 0x00000004;

   
    public static final int STATIC           = 0x00000008;

   
    public static final int FINAL            = 0x00000010;

    
    public static final int SYNCHRONIZED     = 0x00000020;

     
    public static final int VOLATILE         = 0x00000040;

      
    public static final int TRANSIENT        = 0x00000080;

     
    public static final int NATIVE           = 0x00000100;

      
    public static final int INTERFACE        = 0x00000200;

     
    public static final int ABSTRACT         = 0x00000400;

     
    public static final int STRICT           = 0x00000800;
上面的是Modifier里面定义的静态属性

并且每一个都定义了一个判读方法如

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


ReflectionUtils这个反射工具类有几个工具方法,首先介绍几个控制访问权限的方法makeAccessible

它由3个重载,分别是对属性,方法和构造


属性

	public static void makeAccessible(Field field) {
		if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
				Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
			field.setAccessible(true);
		}
	}
方法
public static void makeAccessible(Method method) {
		if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
				&& !method.isAccessible()) {
			method.setAccessible(true);
		}
	}
构造
	public static void makeAccessible(Constructor<?> ctor) {
		if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers()))
				&& !ctor.isAccessible()) {
			ctor.setAccessible(true);
		}
	}

Spring 反射工具类ReflectionUtils