编程语言
首页 > 编程语言> > Javassist:将静态类字段初始化为给定值?

Javassist:将静态类字段初始化为给定值?

作者:互联网

我想将一些对象实例绑定到使用Javassist创建的类.
此对象是从某些源读取的,数据不是预先知道的.

    // Create the class.
    CtClass subClass = pool.makeClass( fullName );
    final CtClass superClass = pool.get( Foo.class.getName() );
    subClass.setSuperclass( superClass );

    // Add a static field containing the definition. // Probably unachievable.
    final CtClass defClass = pool.get( SomeMetaData.class.getName() );
    CtField defField = new CtField( defClass, "DEF", subClass );
    defField.setModifiers( Modifier.STATIC );
    subClass.addField( CtField.Initializer.??? );

    return subClass.toClass();

但是当我检查API时,似乎Javassist创建了一个真正的字节码,它以“调用this”或“实例化那个”或“使用这个常量”的方式存储初始化.

有没有办法让Javassist添加一个初始化为运行时给定的现有实例的静态字段?

解决方法:

你可以像这样具体的初始化器:

// Create the class.
CtClass subClass = pool.makeClass( fullName );
final CtClass superClass = pool.get( Foo.class.getName() );
subClass.setSuperclass( superClass );

// Add a static field containing the definition. // Probably unachievable.
final CtClass defClass = pool.get( SomeMetaData.class.getName() );
CtField defField = new CtField( defClass, "DEF", subClass );
defField.setModifiers( Modifier.STATIC );
subClass.addField( defField, CtField.Initializer.byNew(defClass) );

return subClass.toClass();

这相当于创建以下内容

class fullName extends Foo {
    static SomeMetaData DEF = new SomeMetaData();
}

标签:java,initialization,static,javassist,bytecode-manipulation
来源: https://codeday.me/bug/20190629/1326645.html