java 添加方法

java 添加方法,第1张

CGLib(Code Generation Library)是一个强大的,高性能,高质量的字节码 *** 作类库,它可以在运行期扩展Java类与实现Java接口,Spring、Hibernate等很多著名的框架都使用了它。

使用cglib动态为Java类添加方法

public class CGLibExample {

@SuppressWarnings("unchecked")

public static void main(String[] args) {

// 定义一个参数是字符串类型的setCreatedAt方法

InterfaceMaker im = new InterfaceMaker()

im.add(new Signature("setCreatedAt", Type.VOID_TYPE,

new Type[] { Type.getType(String.class) }), null)

Class myInterface = im.create()

Enhancer enhancer = new Enhancer()

enhancer.setSuperclass(ExampleBean.class)

enhancer.setInterfaces(new Class[] { myInterface })

enhancer.setCallback(new MethodInterceptor() {

public Object intercept(Object obj, Method method, Object[] args,

MethodProxy proxy) throws Throwable {

ExampleBean bean = (ExampleBean) obj

// 调用字符串类型的setCreatedAt方法时,转换成Date型后调用Setter

if (method.getName().startsWith("setCreatedAt")

&&args[0] != null &&args[0] instanceof String) {

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd")

Date date = null

try {

date = sdf.parse((String) args[0])

} catch (final Exception e) { /* nop */ }

bean.setCreatedAt(date)

return null

}

return proxy.invokeSuper(obj, args)

}

})

// 生成一个Bean

ExampleBean bean = (ExampleBean) enhancer.create()

bean.setId(999)

try {

Method method = bean.getClass().getMethod("setCreatedAt", new Class[] {String.class})

method.invoke(bean, new Object[]{"20100531"})

} catch (final Exception e) {

e.printStackTrace()

}

System.out.printf("id : [%d] createdAt : [%s]\n", bean.getId(), bean.getCreatedAt())

}

}

class ExampleBean implements Serializable {

private static final long serialVersionUID = -8121418052209958014L

private int id

private Date createdAt

public int getId() {

return id

}

public void setId(int id) {

this.id = id

}

public Date getCreatedAt() {

return createdAt

}

public void setCreatedAt(Date createdAt) {

this.createdAt = createdAt

}

}

给某个对象动态不了属性的

但是可以通过集合类来实现

例如你可以用Map这个类来实现

map.put(key,value)

键值对都是泛型

之后通过map.get(key)来获取

可以的,我说说大概思路,很简单,你自己具体实现吧,把代码写给你没意义的:

1.将你这段字符串输出到一个文件里,用Java类文件的方式命名。

2.调用外部javac命令将该文件编译。

3.用类加载器(ClassLoad)动态加载新的class文件并用Class.forName()注册该类,然后就可以正常使用了。

上面的每一步都能在baidu中找到实现方法,自己发挥吧。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11616383.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存