java将字符串转换成代码_Java将字符串转换为代码

小编典典

如果你使用的是Java 6,则可以尝试使用Java Compiler API。其核心是JavaCompiler类。你应该能够Comparator在内存中构造对象的源代码。

警告:由于某些奇怪的原因,我的平台上不存在JavaCompiler对象,因此我实际上并未尝试下面的代码…

警告:编译任意Java代码可能会危害你的健康。

考虑一下自己被警告…

String comparableClassName = ...; // the class name of the objects you wish to compare

String comparatorClassName = ...; // something random to avoid class name conflicts

String source = "public class " + comparatorClassName + " implements Comparable {" +

" public int compare(" + comparableClassName + " a, " + comparableClassName + " b) {" +

" return " + expression + ";" +

" }" +

"}";

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

/*

* Please refer to the JavaCompiler JavaDoc page for examples of the following objects (most of which can remain null)

*/

Writer out = null;

JavaFileManager fileManager = null;

DiagnosticListener super JavaFileObject> diagnosticListener = null;

Iterable options = null;

Iterable classes = null;

Iterable extends JavaFileObject> compilationUnits = new ArrayList extends JavaFileObject>();

compilationUnits.add(

new SimpleJavaFileObject() {

// See the JavaDoc page for more details on loading the source String

}

);

compiler.getTask(out, fileManager, diagnosticListener, options, classes, compilationUnits).call();

Comparator comparator = (Comparator) Class.forName(comparableClassName).newInstance();

之后,你只需要在数据库字段中存储适当的Java表达式,a并引用和即可b。

2020-03-02

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值