java - 在运行时添加@XmlTransient注释(与自己的注释结合)

标签 java glassfish classloader classcastexception javassist

自从有一天我就陷入了这个问题。但首先我想描述一下为什么我要走所示的路:

我们正在使用 EE7 和 Glassfish4 在 Java 中构建 RESTful API。身份验证和授权必须由我们自己构建(学生项目)。所以我们的想法是为@AccesRight 和@Roles 添加我们自己的注释。在解释了模型的每个 set 和 get 方法上的元数据(如果已声明)后,应在运行时设置 @XmlTransient 注释,而用户无权查看此注释。简而言之:在模型属性上授予不同的访问权限。

我尝试修改 _model-class-methods 中的方法注释(请参阅方法签名),但是当我运行“.toClass()”时,它失败了,因为 WebAppClassLoader 已经加载了一个类(重复条目)。因此,我决定使用给定模型的另一个名称(_model.getClass().getName() + transactionToken)创建一个副本。大问题:我无法再将此副本转换为原始模型(我得到 ClassCastException)。类和复制类存储在同一个类加载器中。

所以我考虑调用一个方法,例如“loadModelByEntity(UserModel _model)”存储在所有模型中。问题是:运行我的复制类的 .toClass() 后,方法签名现在如下所示: loadModelByEntity(UserModel020a8e6bb07c65da3e9095368db34e843c0b0d1e _model)

Javassist 正在更改类中的所有数据类型。

有什么方法可以防止这种情况或用数据填充我的复制模型吗?有什么办法可以类型转换我的复制模型吗?

非常感谢! 菲尔

//my annotation interface
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target( { ElementType.TYPE, ElementType.METHOD} )
public @interface AccessRight
{
    String  name()    default "";
    Role[]  roles()   default {};
    boolean self()    default true;
    boolean friends() default true;
}




//my method where i analyse the annotation (and perhaps set a new one)
public Object filter(Object _model, String _transactionToken) throws Exception
{

    String className  = _model.getClass().getName() + transactionToken;
    ClassPool pool    = ClassPool.getDefault();    
    CtClass copyClass = pool.getOrNull(className);

    if(copyClass != null)
    {
        Class filterModel     = copyClass.getClass().getClassLoader().loadClass(className);
        Object filterInstance = filterModel.newInstance();

        filterInstance.getClass().getDeclaredMethod("loadByEntity", _model.getClass()).invoke(filterInstance, _model);

        return filterInstance;
    }

    pool.insertClassPath(new ClassClassPath(_model.getClass()));         

    pool.makeClass(className);
    copyClass = pool.getAndRename(_model.getClass().getName(), className);

    ClassFile copyClassFile = copyClass.getClassFile();
    ConstPool constPool = copyClassFile.getConstPool();

    AnnotationsAttribute attribute = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
    Annotation          annotation = attribute.getAnnotation("javax.xml.bind.annotation.XmlTransient");

    if(annotation == null)
    {
        attribute.addAnnotation(new Annotation("javax.xml.bind.annotation.XmlTransient", constPool));
    }

    for(CtMethod method : copyClass.getDeclaredMethods())
    {
        if(method.hasAnnotation(AccessRight.class))
        {
            AccessRight arAnnotation = (AccessRight)method.getAnnotation(AccessRight.class);

            if(!checkAccess(arAnnotation.name(), arAnnotation.roles(), arAnnotation.friends(), arAnnotation.self()))
            {
                method.getMethodInfo().addAttribute(attribute);
            }
        }
    }

    return copyClass.toClass().newInstance();
}


//my consideration to fill the copy model (but it doesn`t work, like i described)
public void loadByEntity(UserModel _model)
{     
    this.m_id               = _model.getId();
    this.m_firstname        = _model.getFirstname();
    this.m_lastname         = _model.getLastname();
    this.m_username         = _model.getUsername();
    this.m_birthday         = _model.getBirthday();
    this.m_email            = _model.getEmail();
    this.m_password         = _model.getPassword();
    this.m_roleId           = _model.getRoleId();
    this.m_timestampCreated = _model.getTimestampCreated();
    this.m_accessRightList  = _model.getAccesRightList();
}

最佳答案

我通过在复制类的运行时删除方法“loadByEntity”(这是Settings.ENTITY_LOAD_METHODNAME)解决了这个问题。然后,我使用原始类中的自定义 Signature 和 javassist codeAttribute 将方法读取到复制类。我还添加了原始类作为转换问题的父类(super class)。所以我的签名看起来不错,而且我可以转换到原始模型。这些方法现在全部被覆盖,因为签名是相同的。

    String className  = _model.getClass().getName() + _transactionToken + Helper.getUnixTimestamp() / Math.random();

    ClassPool pool    = ClassPool.getDefault();    
    pool.insertClassPath(new ClassClassPath(_model.getClass())); 

    CtClass copyClass       = pool.getAndRename(_model.getClass().getName(),className);
    CtClass originalClass   = pool.get(_model.getClass().getName());
    ClassFile copyClassFile = copyClass.getClassFile();
    ConstPool constPool     = copyClassFile.getConstPool();

    copyClass.setSuperclass(pool.get(_model.getClass().getName()));
    copyClass.removeMethod(copyClass.getDeclaredMethod(Settings.ENTITY_LOAD_METHODNAME));

    //creates a new method without codeattribute BUT(!) it is abstract
    CtMethod newLoadMethod = new CtMethod(CtClass.voidType, Settings.ENTITY_LOAD_METHODNAME, new CtClass[] {originalClass}, copyClass);
    CtMethod oldLoadMethod = originalClass.getDeclaredMethod(Settings.ENTITY_LOAD_METHODNAME);

    //set modifier to NOT abstract
    newLoadMethod.setModifiers(newLoadMethod.getModifiers() & ~Modifier.ABSTRACT);
    //set the old code attribute
    newLoadMethod.getMethodInfo().setCodeAttribute(oldLoadMethod.getMethodInfo().getCodeAttribute());
    copyClass.addMethod(newLoadMethod);

关于java - 在运行时添加@XmlTransient注释(与自己的注释结合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17421514/

相关文章:

java - 使用 @Resource 时处理 EJB 上的异常

Java,网络服务 : do I need Tomcat/GlassFish or any other server to run a simple "web service"

java - 反射代理 - 类加载器问题的可见性

java - 类锁定与 java 类加载器有关吗?

java - 如何使用java apache POI :showing java. io.IOException在Excel中写入:流关闭错误

java - 是否有适用于 Netbeans 6.5 或更高版本的 Apache Velocity 插件?

java - 如何在Java 8中查找下个月的第一个星期日?

tomcat - 从 glassfish 3 迁移到 tomcat 7

java - 获取 Java 类加载引用层次结构

java - 为特殊字符生成 AWT keyevent