首页 新闻 会员 周边 捐助

java JDK动态代理和cglib动态代理最后获取的代理对象都为null的问题

0
悬赏园豆:20 [已解决问题] 解决于 2021-01-08 11:30

1、JDK动态代理获取代理对象

接口 如下:

package com.ecut.mapper;

public interface ReactHouse {
public void reathouse();
}

实现类:

package com.ecut.mapper.impl;

import com.ecut.mapper.ReactHouse;

public class UserImpl implements ReactHouse{

@Override
public void reathouse() {
System.out.println("我要买房子");

}

}

jdk动态代理获取类:

package com.ecut.service;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class GetProxy {

private Object target;

public GetProxy(Object target) {
this.target = target;
}

public Object getProxy() {

ClassLoader loader = this.getClass().getClassLoader();

Class[] interfaces = target.getClass().getInterfaces();

InvocationHandler  h = new InvocationHandler () {

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		
		return null;
	}
	
};
Object agency = Proxy.newProxyInstance(loader, interfaces, h);
return agency;

}

}

运行类:
package com.ecut.test;

import com.ecut.mapper.ReactHouse;
import com.ecut.mapper.impl.UserImpl;
import com.ecut.service.GetProxy;

public class Starter {
public static void main(String[] args) {

ReactHouse target = new UserImpl();
GetProxy getProxy = new GetProxy(target);
ReactHouse reactHouse = (ReactHouse)getProxy.getProxy();
reactHouse.reathouse();

// UserImpl userImpl = new UserImpl();
// CglibProxy proxy = new CglibProxy(userImpl);
// UserImpl user = (UserImpl)proxy.getProxy();
// user.reathouse();

}

}
从这获取的 reactHouse 对象为null ,问题所在我找到了但不知道如何解决
原因是获取的安全接口为null。。。System.getSecurityManager() == null

2、cglib动态代理获取代理对象

代理对象获取类:
package com.ecut.service;

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

public class CglibProxy {
private Object target;

public CglibProxy(Object target) {
this.target = target;
}

public Object getProxy() {

Enhancer enhancer = new Enhancer();

enhancer.setSuperclass(target.getClass());

MethodInterceptor methodInterceptor = new MethodInterceptor() {

	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		System.out.println("intercept..");
		
		return null;
	}
	
};
enhancer.setCallback(methodInterceptor);
Object object = enhancer.create();
return object;

}

}

运行:

UserImpl userImpl = new UserImpl();
CglibProxy proxy = new CglibProxy(userImpl);
UserImpl user = (UserImpl)proxy.getProxy();
user.reathouse();

运行结果:
intercept..
intercept..
null

获取的user 对象依旧为null想不明白。
刚学,对着视频一步一步来的,有点自闭了。求大神解惑是哪一步出错了,该如何解决呢。

Yougotmesinging的主页 Yougotmesinging | 初学一级 | 园豆:188
提问于:2021-01-08 10:24
< >
分享
最佳答案
0

在你关闭的问题回答了,去看看

收获园豆:20
95的人 | 菜鸟二级 |园豆:330 | 2021-01-08 10:39
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册