动态生成类?你是指动态生成在xml里指定的类吗?不用cglib,只要ClassLoader和反射就可以了。给你个ClassLoader的例子:class MyClassLoader extends ClassLoader
{ private ClassBytes bytes; public MyClassLoader(ClassBytes bytes)
{
this.bytes = bytes;
}
protected Class findClass(String name) throws ClassNotFoundException
{
try
{
return super.findClass(name);
}
catch(ClassNotFoundException e)
{}
try
{
return defineClass(bytes.getClassBytes(name));
}
catch(Exception e)
{
throw new ClassNotFoundException(e.toString(), e);
}
}}class URLClassBytes implements ClassBytes
{ private String url; private BytesGenerator bytes = new BytesGenerator(); public URLClassBytes(String url)
{
this.url = url;
} public URLClassBytes(String url)
{
this(url, false);
} public byte[] getClassBytes(String className) throws IOException
{
bytes.setIn(new URL(url + className.replaceAll("\\.", "/") + ".class").openStream());
return bytes.getBytes();
}}
{ private ClassBytes bytes; public MyClassLoader(ClassBytes bytes)
{
this.bytes = bytes;
}
protected Class findClass(String name) throws ClassNotFoundException
{
try
{
return super.findClass(name);
}
catch(ClassNotFoundException e)
{}
try
{
return defineClass(bytes.getClassBytes(name));
}
catch(Exception e)
{
throw new ClassNotFoundException(e.toString(), e);
}
}}class URLClassBytes implements ClassBytes
{ private String url; private BytesGenerator bytes = new BytesGenerator(); public URLClassBytes(String url)
{
this.url = url;
} public URLClassBytes(String url)
{
this(url, false);
} public byte[] getClassBytes(String className) throws IOException
{
bytes.setIn(new URL(url + className.replaceAll("\\.", "/") + ".class").openStream());
return bytes.getBytes();
}}
就是把类信息存在XML中,然后读取这个XML就可以动态生成以前的那个Object.
相关的两个类是
java.beans.XMLEncoder
java.beans.XMLDecoder
commons-digester-1.8 ◢██◣
◢██████████◣
◢◣███████████◤
◢████◥██████◤
◢█████████ ███◤
█████████◤ ◢████████◣
◥███████◤ ◢█████████◤
◥██████ ███◤ ████
███ ◢██ ◢█◣◥███
███ ███ ███ ███
███ ███ ███ ███
███ ███ ███ ███
███ ███ ███ ███
███ ███◢██◤ ███
███ ██████ ◢███
◢██████ ◥█◤██◤ ◥███
◥██████ ◢██ ◢███◤
◥████ ◢███ ◥███◣
◥█◤ ◢███◤ ████◣
◢███◤ ◥████
◢███◤ ◥███
◥█◤ ◥█◤
digester只是通过xml把xml其中的数据通过指定的方式送到已有的class中,并不会根据类的‘路径’动态生成class。
<?xml version="1.0" encoding="utf-8" ?>
<Excel>
<columns class="cn.bupt.insky.po.User">
<column name="ID" property="id" type="java.lang.Integer" />
<column name="Name" property="name" type="java.lang.String" />
<column name="Email" property="email" type="java.lang.String" />
<column name="Description" property="descn" type="java.lang.String" />
<column name="Date" property="date" type="java.util.Date" />
</columns>
</Excel>
http://www.jopener.com/category/xml-parsers/xstream/另外的可选方案:
common configuration
common beanutil如果数据量非常大,推荐jibx,它用流来读取xml数据(而不是dom),解析速度接近直接处理文本,非常快,缺点是需要注入你的代码
http://www.jopener.com/category/xml-parsers/jibx-binding-xml-to-java-code/我的网站: www.jopener.com
就是用jibx做的解析,我没有数据库,都是用xml存储数据。中文同步版本: www.jopener.cn把.com换成.cn就是中文了