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

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
java JDK动态代理和cglib动态代理最后获取的代理对象都为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想不明白。

刚学,对着视频一步一步来的,有点自闭了。求大神解惑是哪一步出错了,该如何解决呢。

回答

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

以上是 java JDK动态代理和cglib动态代理最后获取的代理对象都为null的问题 的全部内容, 来源链接: utcz.com/a/95476.html

回到顶部