1. 程式人生 > 其它 >註解類的定義和使用

註解類的定義和使用

技術標籤:javajava

定義註解類

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD,ElementType.METHOD})//作用目標,欄位,方法
@Retention(RetentionPolicy.RUNTIME)//作用範圍,整個執行期間
public @interface
AnnotionBase { //定義int型欄位,id,預設值為3 int id() default 3; // 定義string型別的陣列,stValue String[] stValue(); }

反射獲取屬性

package com.ny;

import com.ny.base.annotion.AnnotionBase;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.SQLOutput;

public class App {
    @AnnotionBase
(stValue = {"male", "female"}) public void getUser(String name, int age) { System.out.println("user: [" + name + "," + age + "]"); } @AnnotionBase(id = 3, stValue = {"kj"}) public int age; public static void main
(String[] args) throws Exception { App app = new App(); Class<? extends App> aClass = app.getClass(); Field age = aClass.getField("age"); AnnotionBase annotation1 = age.getAnnotation(AnnotionBase.class); System.out.println(annotation1.id()+"id"); for (String s : annotation1.stValue()) { System.out.println("stValue"+s); } Method getUser = aClass.getMethod("getUser", String.class, int.class); getUser.invoke(app,"ff",3); AnnotionBase annotation = getUser.getAnnotation(AnnotionBase.class); String[] strings = annotation.stValue(); for (String string : strings) { System.out.println(string); } System.out.println(annotation.id()); } }