看例子 :
自定义注解:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target ({ElementType.METHOD})
@Retention (RetentionPolicy.RUNTIME)
public @interface MyTest {
String value();
}
定义注解时,注意几点:
这两个元注解:
@Target : 表示在允许在哪里添加注解 方法上面 , 类 ,包, 还是字段!!
@Retention : 表示什么时候注解发回作用!
有三种策略:
Class : 字节码 , class文件中!
Source : 源代码中
Runtime : 运行的时候
使用注解:
public class TestClass {
@MyTest("This is Method 1")
public String Method1(String s) {
System.out.println(s);
return s;
}
public String Method2(String s) {
System.out.println(s);
return s;
}
@MyTest("This is Method 3")
public String Method3(String s) {
System.out.println(s);
return s;
}
}
自定义注解要实现什么功能?
这里我们只是简单的取得注解中的属性然后输出即可!如果没有被注解标记 就不调用该方法!
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Main {
// main 方法测试!
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException {
String className = "TestClass";
getAndPrint(className);
}
// 实现注解的功能!! 通过反射机制
// 通过给定的类名,得到相应的类 及它所有的方法
// 然后检测方法是否被标记,如果标记了就把注解的参数传入并输出!!
// 到此,实现了一个简单的注解!
static void getAndPrint(String className) throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, ClassNotFoundException {
Class c = Class.forName(className);
Method[] ms = c.getDeclaredMethods();
for (Method m : ms) {
// 这个方法是否被注解标记
if (m.isAnnotationPresent(MyTest.class)) {
MyTest tc = m.getAnnotation(MyTest.class);
Object o = c.newInstance();
String s = tc.value();
m.invoke(o, s);
}
}
}
}

被折叠的 条评论
为什么被折叠?



