是不是可以形象地比喻为 动态注入 注入内容是类的定义。defineClass protected final Class<?> defineClass(String name, byte[] b, int off, int len) throws ClassFormatError Converts an array of bytes into an instance of class Class. Before the Class can be used it must be resolved. This method assigns a default ProtectionDomain to the newly defined class. The ProtectionDomain is effectively granted the same set of permissions returned when Policy.getPolicy().getPermissions(new CodeSource(null, null)) is invoked. The default domain is created on the first invocation of defineClass, and re-used on subsequent invocations. To assign a specific ProtectionDomain to the class, use the defineClass method that takes a ProtectionDomain as one of its arguments.字节数组b代表的是类的定义,可以在程序运行时动态注入,如果进一步涉及到平地字节码如何构建的问题,就要像楼上他们说的查阅jvm规范了。
JDK 的动态代码是根据 JVM 中 class 文件格式规范,在内存中创建一个 class 数据对象,再用当前的 ClassLoader 加载这个类。
书籍的话推荐看周志明大神的JVM方面的书。
你想动态写不存在的java类代码,我所知道那是不行的。
当然你可以借助外部工具,就当前进程的java而言,应该是找不到这个类的。如果是生成类对象,那很easy!
protected final Class<?> defineClass(String name,
byte[] b,
int off,
int len)
throws ClassFormatError
Converts an array of bytes into an instance of class Class. Before the Class can be used it must be resolved.
This method assigns a default ProtectionDomain to the newly defined class. The ProtectionDomain is effectively granted the same set of permissions returned when Policy.getPolicy().getPermissions(new CodeSource(null, null)) is invoked. The default domain is created on the first invocation of defineClass, and re-used on subsequent invocations. To assign a specific ProtectionDomain to the class, use the defineClass method that takes a ProtectionDomain as one of its arguments.字节数组b代表的是类的定义,可以在程序运行时动态注入,如果进一步涉及到平地字节码如何构建的问题,就要像楼上他们说的查阅jvm规范了。
需要使用javax.tools.ToolProvider、JavaCompiler、JavaFileObject、StandardJavaFileManager等工具类