cglib生成代理对象为null?
向createProxy和getProxy这两个方法传了个接口类型的类,为什么生成代理对象为null呢【吐血】大佬们救救
public class ObjectProxy implements MethodInterceptor { private static Logger log = LoggerFactory.getLogger(ObjectProxy.class);
private static final Map<Class<?>, Object> PROXY_MAP = new ConcurrentHashMap<>();
private final Client client;
private final String serviceName;
private final String interfaceName;
private static final AtomicInteger RPC_ID = new AtomicInteger(10000);
private ObjectMapper objectMapper = new ObjectMapper();
public ObjectProxy(Client client, String serviceName, String interfaceName) {
this.client = client;
this.serviceName = serviceName;
this.interfaceName = interfaceName;
}
public Object createProxy(Class<?> clazz) {
//创建动态代理增强类
Enhancer enhancer = new Enhancer();
//设置类加载器
enhancer.setClassLoader(clazz.getClassLoader());
//设置被代理类
enhancer.setSuperclass(clazz);
//拦截触发回调执行intercept
enhancer.setCallback(this);
return enhancer.create();
}
@SuppressWarnings("unchecked")
public <T> T getProxy(Class<T> clazz) {
try {
T proxy = (T) PROXY_MAP.computeIfAbsent(clazz, (this::createProxy));
if (proxy == null) {
log.error("Failed to create proxy for class {}", clazz.getName());
}
return proxy;
} catch (Exception e) {
log.error("Error creating proxy for class {}", clazz.getName(), e);
}
return null;
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
Object[] params = new Object[objects.length];
for (int i = 0; i < objects.length; i++) {
params[i] = objectMapper.writeValueAsString(objects[i]);
}
//TODO Client发送请求
RpcRequest rpcRequest = new RpcRequest();
rpcRequest.setMethodName(method.getName());
rpcRequest.setServiceName(serviceName);
rpcRequest.setInterfaceName(interfaceName);
rpcRequest.setParameterTypes(method.getParameterTypes());
rpcRequest.setParameterValues(params);
rpcRequest.setRpcId(RPC_ID.getAndIncrement());
return client.sendRequest(rpcRequest);
}
}
回答:
public class ObjectProxy implements InvocationHandler { // ... 其他代码 ...
public Object createProxy(Class<?> clazz) {
return Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, this);
}
// ... 其他代码 ...
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 在此处实现方法拦截逻辑
}
}
以上是 cglib生成代理对象为null? 的全部内容, 来源链接: utcz.com/p/945145.html