自定义注解和动态代理
2.自定义注解的使用
注解类
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface StringDT {
String value() default "defa";
}
测试
需要注意类上面的注解,还是属性上面的,还是方法。以及属性为对象所有,所以在getClass时应该用对象
@Builder
@Data
public class PeopleTest {
@StringDT("zhegege")
private String name;
@NotNull
private Integer age;
public PeopleTest(String name, Integer age) {
System.out.println("youcan");
this.name = name;
this.age = age;
}
public PeopleTest() {
System.out.println("wucan");
}
}
class A{
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
PeopleTest ioi = PeopleTest.builder().name("sea").build();
Class<? extends PeopleTest> aClass = ioi.getClass();
Field field = aClass.getDeclaredField("name");
field.setAccessible(true);
System.out.println(field.getName());
System.out.println(field.isAnnotationPresent(StringDT.class));
StringDT annotation = field.getDeclaredAnnotation(StringDT.class);
if (annotation != null){
System.out.println(annotation.value());
}
}
}
3.动态代理
jdk动态代理
接口
public interface Cat {
void say();
}
实现类
public class CatImpl implements Cat {
@Override
public void say() {
System.out.println("喵喵喵");
}
}
代理
public class JdkProxyTest implements InvocationHandler {
private Object target = null;
public Object getInstance(Object target){
this.target = target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before");
Object invoke = method.invoke(target, args);
System.out.println("after");
return invoke;
}
}
class B{
public static void main(String[] args) {
Cat test = (Cat) new JdkProxyTest().getInstance(new CatImpl());
test.say();
}
}
cglib动态代理
类方法
public class CatImpl {
public void say() {
System.out.println("喵喵喵");
}
}
代理
public class CglibProxyTest implements MethodInterceptor {
public Object getInstance(Object target){
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("cglib before");
Object invoke = methodProxy.invokeSuper(o, objects);
System.out.println("cglib after");
return invoke;
}
}
class D{
public static void main(String[] args) {
CglibProxyTest cglibProxyTest = new CglibProxyTest();
CatImpl cat=(CatImpl)cglibProxyTest.getInstance(new CatImpl());
cat.say();
}
}
https://juejin.cn/post/6844904097150320653