enhacer.create()为单独的bundle中的类返回null

时间:2016-04-29 03:47:38

标签: java reflection osgi

我们使用CGLIB API开发了一个Change Watcher。基于以下示例

  

班主任

import java.util.List;

public class Teacher {

private String userName;
private String cource;
private List<Student> students;

public List<Student> getStudents() {
    return students;
}

public void setStudents(List<Student> students) {
    this.students = students;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getCource() {
    return cource;
}

public void setCource(String cource) {
    this.cource = cource;
}
}
  

Student.class

public class Student {

private String name;
private int age;

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;
}
}
  

ClassFacadeCglib.class

 public class ClassFacadeCglib implements MethodInterceptor{

 private Object target; 

 public Object getInstance(Object target) {  
    this.target = target;  
    Enhancer enhancer = new Enhancer();  
    enhancer.setSuperclass(this.target.getClass());  
    // callback method
    enhancer.setCallback(this);  
    // create proxy object
    return enhancer.create();  
 }  

 @Override
 public Object intercept(Object obj, Method method, Object[] args,  
        MethodProxy proxy) throws Throwable {
    if(method.getName().startsWith("set")){
        System.out.println(method.getName()+" start");  
        proxy.invokeSuper(obj, args);  
        System.out.println(method.getName()+" end..");  
    }
    if(method.getName().startsWith("get")){
        System.out.println(method.getName()+" start");  
        proxy.invokeSuper(obj, args);  
        System.out.println(method.getName()+" end");  
    }
    return null;  
}

}

  

Main.class       公共课主要{

 public static void main(String[] args) {  
        ClassFacadeCglib cglib=new ClassFacadeCglib();  
        Teacher teacher=(Teacher)cglib.getInstance(new Teacher());  
        teacher.setCource("Math");
        teacher.getUserName(); 
 } 

 }

如果这些类属于同一个包和bundle,则enhancer.create()返回我们可以在类的Setters上执行拦截器进程的代理对象。

但是,如果将拦截器类的bundle和包分开,enhacer.create()返回null并阻止我们使用拦截器进程,那么我们需要遵循不同的方法。 分离bundle和package背后的想法是保持开发人员代码与框架代码不同,并限制外部世界了解字节代码的使用情况。 总结一下这个事实。

A类和B类(教师和学生类)候选人候​​选人出现在包X(开发者包)

D类是拦截器类(上面提到的CGlib类),C类是Framework类,它们都存在于框架包中。

 Package Developer 
     Class Delegate
      {
         C c =new C()
        Teacher teach =(Teacher) c.write(new Teacher());
       }

 Package Framework
  Class C
{
 Public Object write(Object model)
   {

     ClassFacadeCglib cglib=new ClassFacadeCglib();  
       Object obj=(Object )cglib.getInstance(model);  //calls returns 
             enhancher.create() as null and thus we cannot perform the interceptor steps

     return obj;


   }

}

0 个答案:

没有答案