2011-03-28 293 views
0

我需要編寫代碼來模擬在運行時在類中提供用戶定義數量的字段。這個想法是能夠將指向這些「動態」字段的java.reflect.Field對象返回給客戶端代碼。將數組項目動態映射到java.reflect.Field對象

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

是否有類似DynamicProxy(但字段)? 感謝

回答

0

最後我用了Javassist到: - 在運行時,從我的原班 繼承創建一個新的類定義 - 注入,我需要爲新的類定義的字段

我也換成了公共構造通過一個靜態工廠方法來創建和返回新類定義的一個實例。總而言之,代碼如下所示:

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

}

相關問題