我想設置一個小元模型以引用多個類的某些屬性。處理meta類(引用屬性)
例:使用下面的課,我想只有Person.name
和Person.surname
存儲在MetaManager.config
。問題是,我不想存儲name
和surname
的值,但是是對該字段的引用。通過存儲這些字段的引用,稍後我可以檢索Person
的任何實例的name
和surname
,我將傳遞給MetaManager.getValues()
。
此代碼與Metamodel API類似,儘管我不確定是否應該使用此代碼(因爲元模型是persistence
的一部分,與persistence
無關)。在此API中,使用EntityType
對象的參考號是Person_.name
。
問題是,我可以以什麼方式存儲對這些屬性的引用,以便稍後可以從實例中檢索這些屬性的值?
下面的代碼給出了我試圖完成的草圖。正如你所看到的,我的問題在Person.getValue()
和toString()
就此參考(因此參考ssn
將因此返回"ssn"
)。
interface IMetable {
Object getValue(Meta meta);
}
class Person implements IMetable {
String ssn;
String name;
String surname;
Person(String ssn, String name, String surname) {
this.ssn = ssn;
this.name = name;
this.surname = surname;
}
@Override
Object getValue(ClassMeta meta) {
// Return the value of the (by meta) referenced field
return null;
}
}
class MetaManager {
Map<Class, Meta[]> config;
public Map<String, String> getValues(IMetable object) {
if(config.containsKey(object.class)) {
ClassMeta[] metamodel = config.get(object.class);
Map<String, String> values = new HashMap();
for(Meta meta : metamodel) {
values.put(meta.toString(), object.getValue(meta).toString());
}
return values;
}
else {
throw new Exception("This class has not been configurated.");
}
}
}
是的是的! Reflection API是我正在尋找的,我怎麼可能沒有想到這一點。 +1 :) – Aquillo 2013-05-02 08:48:30