我可以在Hibernate中从XML映射文件中调用一些方法吗?

时间:2015-07-14 14:33:42

标签: java xml hibernate hibernate-mapping

我有一些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>

1 个答案:

答案 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);
    }
}