一、基本的Demo
1、自定义注解类
MyAnno
package com.zhou.annocation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno {
public String value();
}
2、Mapper接口
TestMapper
package com.zhou.dao;
import com.zhou.annocation.MyAnno;
public interface TestMapper {
@MyAnno("select * from ...")
void selectAll();
@MyAnno("insert into ..")
void insert();
}
3、Test类
Test
package com.zhou.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.zhou.annocation.MyAnno;
import com.zhou.dao.TestMapper;
public class Test{
public static void main(String[] args) {
ClassLoader loader = TestMapper.class.getClassLoader();
TestMapper tm = (TestMapper) Proxy.newProxyInstance(loader, new Class[] {TestMapper.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
MyAnno myAnno = method.getDeclaredAnnotation(MyAnno.class);
String value = myAnno.value();
System.out.println(value);
return null;
}
});
tm.insert();
}
}
输出:insert into …