How to modify property values through reflection

27 views Asked by At

I am currently writing an rpc framework. Now I hope that when the consumer adds @RpcReference to the attribute, the program can automatically scan and inject the attribute. However, after creating the proxy object, the familiar injection is unsuccessful. (Test project is not using spring) field.setAccessible(true); field.set(clazz, proxyConfig.get());

public class BookServiceImpl implements BookService {

    @RpcReference
    private UserService userService;
}

for (Field field : fieldList) {
    Class<?> fieldType = field.getType();
    Class<?> aClass = null;
    try {
        aClass = Class.forName(fieldType.getTypeName());
        log.info("Class -> {}", aClass);
        } catch (ClassNotFoundException e) {
         throw new RuntimeException(e);
    }
    ProxyConfig<?> proxyConfig = new ProxyConfig<>(aClass);
    try {
        field.setAccessible(true);
        field.set(clazz, proxyConfig.get());
    } catch (Exception e) {
        throw new RuntimeException("Failed to set proxy instance to field: " + field.getName(), e);
    }
}
Exception in thread "main" java.lang.RuntimeException: Failed to set proxy instance to field: userService
    at com.dcy.rpc.bootstrap.DRpcBootstrap.reference(DRpcBootstrap.java:138)
    at com.dcy.rpc.Consumer.main(Consumer.java:21)
Caused by: java.lang.IllegalArgumentException: Can not set com.dcy.rpc.UserService field com.dcy.rpc.service.impl.BookServiceImpl.userService to 

I hope to complete the injection by modifying the attribute value

0

There are 0 answers