繁体   English   中英

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

[英]Can I invoke some method from XML mapping file in Hibernate?

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

使用反射

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM