通过注解注入对象使用.annotationType().getDeclaredMethods()得到

本文介绍了一个使用Java反射和注解技术实现属性自动注入的例子。通过定义Person类及其属性,并利用自定义注解Injection来标记需要注入的属性,再借助反射机制获取并设置这些属性值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Person类
package com.introspector;

public class Person {
private String name;
private int age;
private boolean gender;

public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

}


PersonDao类

package com.introspector;

public class PersonDao {
private Person person;

public Person getPerson() {
return person;
}

@Injection(name="张一", age=11, gender=false)
public void setPerson(Person person){
this.person = person;
}
}


Injection类


package com.introspector;

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

@Retention(RetentionPolicy.RUNTIME)
public @interface Injection {

String name();

int age();

boolean gender() default true;

}



TestDemo类


//得到PersonDao上person的属性描述器
PropertyDescriptor pd = new PropertyDescriptor("person", PersonDao.class);
Class clazz = pd.getPropertyType();
Object p = clazz.newInstance();
Method writeMethod = pd.getWriteMethod();

Injection injection = writeMethod.getAnnotation(Injection.class);
//injection.annotationType返回的是interface com.introspector.Injection 接口再直接得到注解接口对应的方法
Method[] methods = injection.annotationType().getDeclaredMethods();
Field f = null;
for(Method m : methods){
//直接往person的属性中注入
f = p.getClass().getDeclaredField(m.getName());
f.setAccessible(true);
f.set(p, m.invoke(injection, null));
}

PersonDao pdo = new PersonDao();
writeMethod.invoke(pdo, p);
System.out.println(pdo.getPerson().getAge());
System.out.println(pdo.getPerson().getName());
System.out.println(pdo.getPerson().isGender());
在做 javaagent 时 ,使用 agentMain 对已经运行中的 springboot 应用中的 restController 的 postmapping 修饰的方法 做切面,注意这里是 agentMain ,以下方法执行之前大部分类已经加载结束并且对应的controller生成了单例的bean,package org.sunyaxing.transflow.agent.agentplugin; import net.bytebuddy.agent.ByteBuddyAgent; import net.bytebuddy.agent.builder.AgentBuilder; import net.bytebuddy.implementation.MethodDelegation; import net.bytebuddy.matcher.ElementMatchers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.lang.instrument.Instrumentation; public class TransflowAgent { private static final Logger log = LoggerFactory.getLogger(TransflowAgent.class); public static void agentmain(String agentArgs, Instrumentation instrumentation) { ByteBuddyAgent.install(); new AgentBuilder.Default() .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION) .with(AgentBuilder.TypeStrategy.Default.REDEFINE) .type(ElementMatchers.isAnnotatedWith(RestController.class)) .transform((builder, typeDescription, classLoader, javaModule) -> { log.info("agentmain transform class {} {}", typeDescription, classLoader); return builder .method( ElementMatchers.isAnnotatedWith(RequestMapping.class) .or(ElementMatchers.isAnnotatedWith(GetMapping.class)) .or(ElementMatchers.isAnnotatedWith(PostMapping.class)) ) .intercept(MethodDelegation.to(MonitorInterceptor.class)); }).installOnByteBuddyAgent(); } 然而,注入对已经运行的serverA 注入agent后,调用postmapping所修饰的方法并没有触发切面,是什么原因,如何解决
最新发布
04-03
Caused by: java.lang.NoClassDefFoundError: com/venustech/ca/system/model/SoftwareUpgradeBO at java.lang.Class.getDeclaredMethods0(Native Method) ~[?:1.8.0_231] at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[?:1.8.0_231] at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[?:1.8.0_231] at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:467) ~[spring-core-5.3.23.jar:5.3.23] at org.springframework.util.ReflectionUtils.doWithLocalMethods(ReflectionUtils.java:321) ~[spring-core-5.3.23.jar:5.3.23] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:267) ~[spring-beans-5.3.23.jar:5.3.23] ... 27 more Caused by: java.lang.ClassNotFoundException: com.venustech.ca.system.model.SoftwareUpgradeBO at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1358) ~[catalina.jar:8.5.54] at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1180) ~[catalina.jar:8.5.54] at java.lang.Class.getDeclaredMethods0(Native Method) ~[?:1.8.0_231] at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[?:1.8.0_231] at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[?:1.8.0_231] at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:467) ~[spring-core-5.3.23.jar:5.3.23] at org.springframework.util.ReflectionUtils.doWithLocalMethods(ReflectionUtils.java:321) ~[spring-core-5.3.23.jar:5.3.23] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors(AutowiredAnnotationBeanPostProcessor.java:267) ~[spring-beans-5.3.23.jar:5.3.23]
06-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值