Java 注解
Posted 猪八戒1.0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 注解相关的知识,希望对你有一定的参考价值。
[public] @interface 注解名
// 定义属性
数据类型 属性名() [default 属性值];
package org.lanqiao.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FruitColor
String fruitColor() default "RED";
package org.lanqiao.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FruitName
String value() default "fruit";
package org.lanqiao.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FruitProvider
int id() default 1;
String name() default "苹果集团";
String address() default "洪山区";
package org.lanqiao.entity;
import org.lanqiao.annotation.FruitColor;
import org.lanqiao.annotation.FruitName;
import org.lanqiao.annotation.FruitProvider;
public class Apple
@FruitName(value = "Apple")
public String appleName;
@FruitColor(fruitColor = "RED")
public String appleColor;
@FruitProvider(id=1,name="陕西红富士集团",address = "陕西省西安市未央区红富士大厦")
public String appleProvider;
package org.lanqiao.annotation.test;
import org.lanqiao.annotation.FruitColor;
import org.lanqiao.annotation.FruitName;
import org.lanqiao.annotation.FruitProvider;
import java.lang.reflect.Field;
/**
* 使用反射机制处理自定义注解
*/
public class FruitInfoUtil
public static void main(String[] args) throws Exception
// 加载 AnnotationTest.class类
Class<?> clazz = FruitInfoUtil.class.getClassLoader().loadClass("org.lanqiao.entity.Apple");
// 获取属性
Field[] fields = clazz.getDeclaredFields();
// 遍历属性
for (Field field : fields)
FruitName fn = field.getAnnotation(FruitName.class);
FruitColor fc = field.getAnnotation(FruitColor.class);
FruitProvider fp = field.getAnnotation(FruitProvider.class);
if(fn!=null)
System.out.println("水果名称:" + fn.value());
if(fc!=null)
System.out.println("水果颜色:" + fc.fruitColor() );
if(fp!=null)
System.out.println("水果供应商:供应商编号:"+fp.id()+";供应商名称:"+fp.name()+";供应商地址:"+fp.address());
以上是关于Java 注解的主要内容,如果未能解决你的问题,请参考以下文章