如何生成字节码并保存到.class文件? [英] How to generate bytecode and save to .class file?

查看:236
本文介绍了如何生成字节码并保存到.class文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下奇怪的要求。

我得到:


  1. 一些方法名称的列表。

  2. 上述方法的参数名称和类型。

  3. 上述方法的功能。具体如下:
    对于每个参数,该方法使用 toString 将其转换为字符串,并获取字符串数组。对于此数组,该方法应用函数 foo 。函数 foo 接受 String [] 类型并输出 String 。这些方法返回 foo 返回的内容。
    foo 的代码在Java对象中给出,并作为黑盒访问。

  1. A list of some method names.
  2. Names and types of parameters of the above methods.
  3. The functionality of the above methods. This is as follows: For each parameter, the method converts it to string using toString and obtains an array of strings. To this array, the method applies a function foo. The function foo takes as input a String [] type and outputs String. The methods return what foo returns. foo's code is given inside a Java object and is to be accessed as a black-box.

1.和2中的信息可以是文本或XML文件。为此,我们可以认为它以我们选择的任何方式在Java对象中可用。

The info in 1. and 2. can be in a text or XML file. For this purpose, we can consider it to be available inside a Java object in whatever way we choose.

任务是创建一个实现这些方法的 .class 文件(即字节码),并且可以运行在JVM上。

The task is to create a .class file (i.e., bytecode) that implements those methods and can be run on the JVM.

我认为这个汇编程序库将是一种方式去做吧。任何人都可以提出更简单的方法

I think this assembler library would be one way to do it. Can anyone suggest an easier way?

我可以想到另一种方法:首先生成 .java 文件,然后编译它获取 .class 文件。

I can think of one other way: first generate the .java file and then compile it to get the .class file.

[上下文:]我必须为数百种方法执行此操作。我想要快捷方式,这样我就可以自动完成工作,而不是手动编写代码。

[The context:] I have to do this for several hundreds of methods. I want the shortcut so I can automate my job rather than manually write the code.

推荐答案

您可以使用Java语法生成所需的程序代码,并使用编译器将其转换为类文件。可以在运行时实例化 javac 并传递一个字节数组而不是源文件的位置。对于其他程序员来说,这可能是最容易维护的。

You could generate the required program code in Java syntax and turn it into a class file using the compiler. It's possible to instantiate javac at run time and pass it a byte array instead of the location of the source file. This is probably the easiest for other programmers to maintain.

如果你想直接生成字节码, asm 是最常用的库。

If you want to generate byte code directly, asm is the library most commonly used.

这篇关于如何生成字节码并保存到.class文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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