Java interpreter code at runtime - java

We have discussed how java is first compiled into Java bytecode and then interpreted by the JVM. Build into the program we are using (Dr Java), there is a panel called Interactions where you can type code in real time and have it be interpreted and ran (I believe that is how it works). I was wondering if it was possible to have a compiled program in java be ran, and then allow a user to input java code to be interpreted to modify the things that happen. I can't really think of any practical uses of this, but here is an example to clarify:
User runs a program and an integer in initialized with the value of 2 and the name of changeNumber. A pop-up comes up allowing the user to input some java code. They can input something like - "changeNumber = changeNumber + 2;" and have the code execute in real time where if you ended up printing out changeNumber, you would get 4.

This is possible using the Reflection API.
As a side note, I do not understand the downvotes. This is a good and well-written question for a beginner.

Related

Is there any way that Java could get current file name and current line number?

In C++, the file of the source code and current line number is decided by FILE and INLINE, which is decided at compiling time, is there any method in Java that could do the similar thing? The file and line number is decided at compiling time instead of runtime? this will be convenient for log. I kind of doubt that use runtime method to detect these information will decrease the performance.
You could use Thread.getStackTrace() and something like
System.out.println(Thread.currentThread().getStackTrace()[1]);
Output includes the current method and line number (if debugging was compiled in).
For example,
com.stackoverflow.Main.main(Main.java:23)

How to script input for a Java program

I'm writing a Java program that requires its (technical) users to write scripts that it uses as input; it interprets these scripts into a series of actions and executes them. I am currently looking for the cleanest way to implement the script/configuration language. I was originally thinking of heading down the XML route, but the nature of the required input really is a procedural, linear flow of actions that need to be executed:
function move(Block b, Position p) {
// user-defined algorithm for moving block "b" to position "p"
}
Block a = getBlockA();
Position p = getPositionP();
move(a, p);
Etc. Please note: the above is an example only and does not constitute the exact syntax I am looking to achieve. I am still in the "30,000 ft view"-design phase, and don't know what my concreted scripting language will ultimately look like. I only provide this example to show that it is a flow/procedural script that the users must write, and that XML is probably not the best candidate for its implementation.
XML, perfect for hierarchial data, just doesn't feel like the best choice for such an implementation (although I could force it to work if need-be).
Not knowing a lick about DSLs, I've begun to read up on Groovy DSLs and they feel like a perfect match for what I need.
My uderstanding is that I could write, say, a Groovy (I'm stronger in Groovy than Scala, JRuby, etc.) DSL that would allow users to write scripts (.groovy files) that my program could then execute as input at runtime.
Is this correct, or am I misunderstanding the intent of DSLs altogether? If I am mistaken, does anybody have any suggestions for me? And if I am correct then how would a Java program read and execute a .groovy file (in other words, how would my program "consume" their script)?
Edit: I'm beginning to like ANTLR. Although I would love to roll up my sleeves and write a Groovy DSL, I don't want my users to be able to write any old Groovy program they want. I want my own "micro-language" and if users step outside of it I want the interpreter to invalidate the script. It's beginning to seem like Groovy/DSLs aren't the right choice, and maybe ANTLR could be the solution I need...?
I think you are on a really good path. Your users can write their files using your simple DSL and them you can run them by Evaling them at runtime. Your biggest challenge will be helping them to use the API of your DSL correctly. Unless they use an IDE this will be pretty tough.
Equivalent of eval() in Groovy
Yes, you can write a Groovy program that will accept a script as input and execute it. I recently wrote a BASIC DSL/interpreter in this way using groovy :
http://cartesianproduct.wordpress.com/binsic-is-not-sinclair-instruction-code/
(In the end it was more interpreter than DSL but that was to do with a peculiarity of Groovy that likely won't affect you - BASIC insists on UPPER CASE keywords which Groovy finds hard to parse - hence they have to be converted to lower case).
Groovy allows you to extend the script environment in various ways (eg injecting variables into the binding and transferring execution from the current script to a different, dynamically loaded script) which make this relatively simple.

Is there an equivalent of Vbscript execute statement in Java

To start off, I know that Vbscript is interpreted and Java is compiled. But is there a way to do the tasks of vbscript 'execute' or 'eval' statements in Java? What I am trying to do is to save a piece of code in a variable, and try to execute the saved code during run time.
For eg, in vbscript,
a = "b = 10"
execute(a)
will assign the value 10 to a variable 'b'. If this is possible in java, I can handle a situation,I have got myself in to without redesigning the whole code. Request your help.
No, Java has no equivalent to VBScript's execute.
You could do what you're outlining using scripting for Java, however, where you have a reasonably wide range of scripting languages to choose from.

Log line numbers of executed java code

I am writing part of a PHP web application (which will be used in a high school bug finding contest) where the user must find bugs in a given Java program. As a part of this, when the Java program executes, we want to highlight the lines of the source of the Java program where the code has executed. To do this, all we need are the line numbers of the source that have been executed, that is, the code path (or is it called code coverage?). We will highlight the lines in the source file using the line numbers.
We will be using PHP's shell-exec() to execute the Java program and the tool to get the code path (whatever that will be). What is the easiest way of getting the line numbers of code path?
Thank you very much!
Here is a picture that describes what we would like
PHP interperts the code, which means it runs over the source each time you run the program. This has the benefit of blowing up as the code is read (which makes line number printouts trivial); however, it often is expensive in other ways, as you cannot optimize deeply (or do any pre-runtime error checking).
Java compiles its code into a JVM assembly language called "bytecode." This means that what is running doesn't generally have access to (or even use) the source code. That said, there are techniques. A compiled Java class has the ability to add "extra data" and one of those "extra data elements" is a line number table, which is an index allowing someone running the assembly to "look up" the line number as the compiler recorded it.
This generally works ok, with the considerations that: compilers often don't mark up every instruction, the source code may not be available, optimization might make certain inner chunks of code not function in ways that facilitate pointing to the input code text.
How code coverage tools "fix" this is that they generally insert into the code (at the assembly level) a large number of commands that effectively act as logging statements to a format that allows the tool to determine which path through the code was actually followed. This is then mapped back through the line number table as best as possible and then used to highlight lines within the original source file.
If you want something with finer resolution (something that can process which portion of a line was executed) then you need to dig deeper. Eventually you might even consider writing your own compiler (or compiler extension) which will store your own custom line number table that overcomes the shortcomings of the current solutions.
Tricks like throwing exceptions (as Shiven has mentioned) and parsing out the line number do work; however, they pollute your code with odd exception processing for items that really aren't exceptional, just to "get the line number". Due to the code clutter and the generally poorer runtime performance of exceptions, I tend to avoid such solutions (but they do work).
Anyway, hopefully this will give you a view as to why it doesn't always work exactly the same way as PHP.
You could get a linenumber if you compile the program with the -g option, do a printStackTrace(), capture the trace output and extract the linenumber from there.
Take a look at Cobertura. It computes coverage and stuff like that, and if it doesn't already do it, it should be relatively easy to add the line number collecting to it.
There's a very hackish attempt to do that, but that's so slow that you may not be able to use it in production https://bitbucket.org/jowu/myriapod/wiki/Home
I have never done or seen anything like this but it does seem like an interesting problem. My thought would be to use the java debugger (jdb) to run the code, rather than just the java command.
You can step through the code line by line (via the step command in jdb) and each time a line executes its line number is spit out. This would require a little help from the PHP side (it would have to parse the line number as well as execute the next step command) but the line numbers are there. Here is a sample output from a very basic java program.
Java (TestClass.java)
public class TestClass {
public static void main(String[] args) {
System.out.println("foo");
System.out.println("bar");
}
}
jdb (jdb TestClass after running javac TestClass.java)
Initializing jdb ...
> stop at TestClass:3
Deferring breakpoint TestClass:3.
It will be set after the class is loaded.
> run
run TestClass
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
>
VM Started: Set deferred breakpoint TestClass:3
Breakpoint hit: "thread=main", TestClass.main(), line=3 bci=0
3 System.out.println("foo");
main[1] step
> foo
Step completed: "thread=main", TestClass.main(), line=4 bci=8
4 System.out.println("bar");
main[1] step
> bar
Step completed: "thread=main", TestClass.main(), line=5 bci=16
5 }
main[1] step
>
The application exited
Try referring to this link JVMDI
You can try accessing the values of the program counter and then map it onto the lineNumberTable .
OR
I think JVMDI has a method which can access the line number of the executing code.I'm not sure of the latter,refer the to the link above and hope it helps.

accessing static variable in multi threading system

I have to take one input from console in first java program. That input i have to pass in second java program which is getting executed as thread from the main method of first java program.
I made the variable as static and tried accessing in second java program but it is showing null value(default value).
I am not supposed to make the object of first program also.
Please suggest me how to do?
If your first java program is starting the second using O.S.-like functions that produces the same effect as if you were starting from the console, then you will have a second instance of the JVM, with everything "reseted". That's why you're getting that null.
A suggestion would be passing the value as a parameter for the second program.
As far as I know there's no shared memory mechanism implemented in Java. Pipes also don't work across VM boundaries, so you would have to use the JNI and C code to create a mechanism.
But then if the two programs cooperate that close together, why not let them in one VM and use threads? Security reasons is the only thing I could think of.

Categories

Resources