在运行时将新方法和属性注入类 [英] Inject New Methods and Properties into Classes During Runtime

查看:79
本文介绍了在运行时将新方法和属性注入类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以在运行时向类中注入新的方法和属性.

Is there any way we can inject new methods and properties into classes during run-time.

http://nurkiewicz.blogspot. com/2009/09/injecting-methods-at-runtime-to-java.html 指出,我们可以使用Groovy做到这一点.

http://nurkiewicz.blogspot.com/2009/09/injecting-methods-at-runtime-to-java.html states we may do that by using Groovy.

仅通过使用Java就能做到吗?

Is it possible by just doing using Java?

推荐答案

是否可以通过使用 Java?

Is it possible by just doing using Java?

简单的答案是强调您不想这样做!".

The simple answer is an emphatic "You don't want to do that!".

从技术上讲,这是可行的,但并非没有采取极其复杂,昂贵且易碎的技巧,例如字节码修改 1 .即使这样,您也必须依靠动态加载来访问修改后的类型,并(可能)使用反射来利用其新成员.简而言之,您将为自己制造很多痛苦,几乎没有收获.

It is technically possible, but not without resorting to extremely complex, expensive and fragile tricks like bytecode modification1. And even then, you have to rely on dynamic loading to access the modified type and (probably) reflection to make use of its new members. In short, you would be creating lots of pain for yourself, for little if any gain.

Java是一种静态类型的语言,添加/修改类类型签名可能会破坏类的静态类型协定.

Java is a statically typed language, and adding / modifying class type signatures can break the static typing contract of a class.

1-AspectJ之类的东西可以让您向类中注入其他行为,但可能并非您所追求的运行时"注入.当然,注入的方法将无法用于静态编译的代码调用.

这篇关于在运行时将新方法和属性注入类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆