java控制台执行,如何执行控制台或GUI输入,就像是实际的Java代码?

I want to be able to input java commands/code to execute during run-time (during the execution of a "persistent" program) in the same way, or as close as possible, to the same code would be executed if it was present on the source-code for the program (programmed as part of the software), using a GUI element, like jTextArea.

The following StackOverflow questions seem to be related, but, along with they'r answers, don't seem to be what i'm looking for.

I don't want to "be able to trigger actions from specific console inputs, and print the feedback into the console", as seems to be the case of console applications described in those question and answers.

What i want is to "be able to execute actual java code, that i cannot predict nor control, from console (or GUI) input".

NOTE: The "i cannot predict nor control" here refers to the "developer"...But of course i can predict and "control" it if i'm the one inputting the code, as the "user" would do.

Since java uses a virtual-machine environment, i think it might be possible for it to execute "run-time inputted code"...But i'm not sure such thing is even possible.

For example, i'd like the run-time input of for(int i=0; i<3; i++){System.out.println(i);} in the "GUI console" (jTextArea, for example) to, upon pressing the enter key or clicking a "Send" button, be ("compiled and "?) executed, and give the same output as if it was part of the original source-code, thus:

0

1

2

So i'd like to know the following:

Is it possible?

If yes, how can i do it? (OR, if no, what is the closest alternative?)

解决方案

Use the JavaCompiler. It can compile code from a String.

For an E.G. see the STBC & especially the source code. It provides a GUI and can compile the code in the text area on button click.

LWGH1.png

But note the:

STBC will run on any computer with a version 1.6+ Java Plug-In* JDK (AKA SDK).

(*) The API that STBC uses is merely a public interface to the compiler in the tools.jar that is distributed only with JDKs (though the 'public JRE' of the JDK also seems to acquire a tools.jar). This leads to some unusual requirements in running either the native jar, or the web start app.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值