具体使用Java注解的方式
1.使用预定义注解: 预定义注解是Java提供的一些内置注解,可以直接在代码中使用。例如,@Override、@Deprecated、@SuppressWarnings等。
@Override
public void run() {
// 重写父类的run()方法
// ...
}
@Deprecated
public class OldClass {
// ...
}
@SuppressWarnings("unchecked")
public List<SomeClass> getSomeList() {
// ...
}
2.创建自定义注解: 如果想要自定义注解,需要使用@interface关键字,并指定注解的元素。
@Retention(RetentionPolicy.RUNTIME) // 指定注解保留到运行时
@Target(ElementType.METHOD) // 指定注解适用于方法
public @interface MyAnnotation {
String value();
int count() default 1;
}
3.然后在需要使用该注解的地方进行注解的引用,指定注解的元素值。
public class MyClass {
@MyAnnotation(value = "example", count = 5)
public void myMethod() {
// ...
}
}
4.在运行时,可以使用反射来获取注解的信息。
MyClass obj = new MyClass();
Method method = obj.getClass().getMethod("myMethod");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
String value = annotation.value(); // 获取注解的元素值
int count = annotation.count();
demo
package com.lidaochen.test;
public class CJavaTest {
public void eat()
{
System.out.println("我喜欢吃西瓜!");
}
}
package com.lidaochen.test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Pro {
String className();
String methodName();
}
package com.lidaochen.test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.lang.reflect.Method;
import java.util.Properties;
@Pro(className = "com.lidaochen.test.CJavaTest", methodName = "eat")
public class CJavaDemo {
public static void main(String[] args) throws Exception{
// 1、获取该类的字节码对象
Class cls = CJavaDemo.class;
// 2、获取上边的注解对象
Pro an = (Pro) cls.getAnnotation(Pro.class);
// 3、调用注解对象中定义的抽象方法,获取返回值
String className = an.className();
String methodName = an.methodName();
System.out.println(className);
System.out.println(methodName);
// 4、加载该类进内存
Class mJavaTest = Class.forName(className);
// 创建对象
Object obj = mJavaTest.newInstance();
// 获取方法对象
Method method = mJavaTest.getMethod(methodName);
// 执行方法
method.invoke(obj);
}
}