开发者

dynamically map array items to java.reflect.Field objects

I need to write code that simulates having a user-defined number of fields available in a class at runtime. The idea being to be able to return java.reflect.Field objects pointing to those "dynamic" fields to client-开发者_开发百科code.

class DynamicFieldClass {
 /**
  * fieldNames is the list of names of the fields we want to "exist" in the class
  * they will all be of the same type (say String)
  */
 public DynamicFieldClass(List<String> fieldNames) {
 // ... what do we do here
 }
 public Field getFieldObjectFor(String desiredFieldName) {
 // ... what do we do here
 }
}

Is there something similar to DynamicProxy (but for fields)? Thanks


I ended up using Javassist to : - create a new class definition at runtime that inherits from my original class - inject the fields I needed into the new class definition

I also replaced the public constructor by a static factory method that makes and returns an instance of the new class definition. All in all, the code looks like this:

class DynamicFieldClass {
protected DynamicFieldClass()   {
}    
public Field getFieldObjectFor(String desiredFieldName) {
    return null;
}

/**
* fieldNames is the list of names of the fields we want to "exist" in the class
* they will all be of the same type (say String)
*/
public static createInstance (List<String> fieldNames)  {
    ClassPool defaultClassPool = ClassPool.getDefault(); 
    CtClass originalClass = defaultClassPool.get("DynamicFieldClass");
    CtClass newClass = defaultClassPool.makeClass("modified_DynamicFieldClass", originalClass);

    StringBuilder getterCore = new StringBuilder();        
    for (String item : fieldNames)  {
        CtField addedField = CtField.make(String.format("private String %s;", item), newClass);
        newClass.addField(addedField);
        getterCore.append(String.format("if \"%s\".equals(%1) { return this.class.getDeclaredField(%s);}", item, item));
    }            
    getterCore.append("throw new IllegalArgumentException(\"Unknown field name: \" + $1);");
    final String sourceGeneralGetter = String.format("{%s}", getterCore.toString());
    CtMethod mold = originalClass.getDeclaredMethod("getFieldObjectFor");
    CtMethod copiedMeth = CtNewMethod.copy(mold, newClass, null);
    newClass.addMethod(copiedMeth);
    CtMethod getMeth = newClass.getDeclaredMethod("getFieldObjectFor");
    getMeth.setBody(sourceGeneralGetter);
    CtConstructor defaultCtor = new CtConstructor(new CtClass[0], newClass);
    defaultCtor.setBody("{}");
    newClass.addConstructor(defaultCtor);
    Class modifiedClass = newClass.toClass();
    return modifiedClass.newInstance();
}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜