我有一些xml映射文件。我可以从中调用一些方法吗?
点子:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="pkg.SomeItem" table="item">
<id name="itemId" column="itemId" unsaved-value="0">
<generator class="increment"/>
</id>
<property name="fileSize" invoke="MyFileManager.getActualFileSize(itemId);"/>
</class>
</hibernate-mapping>
答案 0 :(得分:0)
使用Reflection:
// my xml parsing code is incorrect; for illustration purposes only
String className = xml.getElement("class").getAttribute("name").getValue();
String methodName = xml.getAttribute("invoke").getValue();
// get generic instance of class
Class<?> c = Class.forName(className);
Object o = c.newInstance();
// get cast instance
// (although 'f' is of type Object, it will show methods of desired class!)
Object f = c.cast(o);
Method[] methods = f.getClass().getMethods();
for (Method method:methods)
{
if (method.equals(methodName))
{
// invoke desired method
method.invoke(arg0, arg1);
}
}