现在的位置: 首页 > 综合 > 正文

注解与反射

2013年01月08日 ⁄ 综合 ⁄ 共 1021字 ⁄ 字号 评论关闭
package com.elf.myannotation;

import java.lang.annotation.Target;//这个有时候不会提示你导入,要自己导入才能用。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Tough
 *
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)//要使用反射读取注解,必须把注解的保持策略设置为Runtime
@interface PowerJudge{
	int power() default 1;//power值为1代表是普通用户,2代表管理员
}
class PowerClass{
	@PowerJudge(power=2)
	public void Adm(){
		System.out.println("Im administrator");
	}
	@PowerJudge(power=1)
	public void User(){
		System.out.println("Im ordinary user");
	}
}
public class AnnotationAndReflect {
	public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		
		PowerClass pc=new PowerClass();
		Method[] method=pc.getClass().getDeclaredMethods();
		
		for(int i=0;i<method.length;i++){
			PowerJudge pj=method[i].getAnnotation(PowerJudge.class);
			int p=pj.power();
			System.out.println(p);
			if(p==1){
				method[i].invoke(pc, null);
			}
			}
	}
}

 

抱歉!评论已关闭.