JAVA study diary: Notes (5)

The main content learned today:

	1.什么是注解处理器
	2.如何使用其来读取信息

Annotation processor:

	注解处理器能够在程序运行期间将代码中的一些使用注解的信息运用反射机制来得到它,值得一提的是,注解它本身不会影响编译。
	注解处理器的使用前提:
			该注解有@Retention(RetentionPolicy.RUNTIME)

Code!
Test class (main test class):

package LessonForAnnotation05;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test 
{
    
    
	public static void main(String[] args) 
	{
    
    
		int i = 0;
		
		Class<TestWeek> c1 = TestWeek.class;
		Method[] m1 = c1.getMethods();
		
		for (Method m:m1)
		{
    
    
			if (m.isAnnotationPresent(Week.class))
			{
    
    
				try 
				{
    
    
						m.invoke(c1.newInstance());
				} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
						| InstantiationException e) 
						{
    
    
							e.printStackTrace();
						}
			}
		}
		
		for (Method m:m1)
		{
    
    
			if (m.isAnnotationPresent(Week.class))
			{
    
    
				Week w1 = m.getAnnotation(Week.class);//getAnnotation判断该注解是哪个注解
				int a = w1.m();//得到注解中的方法的值
				System.out.println(a);
				
				try 
				{
    
    
					for (i=0; i<a; i++)
					{
    
    
						m.invoke(c1.newInstance());
					}
				} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
						| InstantiationException e) 
						{
    
    
							e.printStackTrace();
						}
			}
		}
	}
}

Week notes:

package LessonForAnnotation05;

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)//这里Retention注解初值是RUNTIME
public @interface Week 
{
    
    
	int m() default 4;
}

TestWeek (annotation method class):

package LessonForAnnotation05;

public class TestWeek 
{
    
    
	@Week
	public void getWeek01()
    {
    
    
    	System.out.println("public void getWeek()");
    }
	
	public void getWeek02()
	{
    
    
		System.out.println("public void getWeek01()");
	}
}

部分文字来源于:
	咕嘟咖啡杨海滨老师 — 《java编程语言高级特性》
	在这里十分感谢老师能够给我带来学习的激情。

2020.10.17
可以转载我的学习日记但请注明出处,谢谢。
本文章是本人学习笔记,不进行任何商用!只为记录本人学习历程。
毕

Guess you like

Origin blog.csdn.net/SIESTA030/article/details/109080044