注解是是一种数据类型, 它是一个标记, 方便java在编译时遇到这个标记能采取进一步的action
@interface
来定义注解接口/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
3. 指定注解的作用目标@Target(ElementType.FIELD)
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// 自定义作用在Field上的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TestField
{
String name();
}
// 自定义在method上的注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface TestAnnotation
{
String name();
int age() default 18;
int[] score();
}
// 测试类
public class Test
{
@TestAnnotation(name = "james", age =18 , score = {23,24})
public void hello(){
System.out.println("");
}
@TestField(name = "james")
private String username;
public static void main(String[] args) throws NoSuchMethodException, NoSuchFieldException
{
// 通过反射来回去method 和 fields
Method method = Test.class.getMethod("hello", null);
Field[] fields = Test.class.getDeclaredFields();
for (Field field: fields) {
if (field.isAnnotationPresent(TestField.class)) {
TestField annotation = field.getAnnotation(TestField.class);
System.out.println("annotation.name() = " + annotation.name());
}
}
if(method.isAnnotationPresent(TestAnnotation.class)){
TestAnnotation tf = method.getAnnotation(TestAnnotation.class);
System.out.println("name: " + tf.name() +" age: "+ tf.age());
}
}
}
// 输出结果
annotation.name() = james
name: james age: 18
https://blog.csdn.net/wangpengzhi19891223/article/details/78131137
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。