Compiling java Code Available In A String within another java code [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
On-the-fly, in-memory java code compilation for Java 5 and Java 6
Compiling Java file with code from within a Java file
i have a hello world class available in the string of a program as given in the example below,
public class CompileJavaString {
public static void main(String arg[]) {
String s="public class HelloWorld{ public static void main(String arg[]) ";
s=s+" { System.out.println(\"Hello World\"); } } ";
// this is the complete code of Hello World class taken as an example
// code to compile the class Hello World available in string and
// generate the HelloWorld.class file required here
}
}
can someone help to compile the code in a memory string available in example given above

You want to have a look at javax.tools.JavaCompiler and related classes.
The documentation contains examples of how to use them.
Note that the java compiler will only work if you have a JDK installed. A JRE is not enough.

Save as HelloWorld.java and do following:
String fileToCompile = "HelloWorld.java";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, fileToCompile);
if(compilationResult == 0){
System.out.println("Compilation is successful");
}else{
System.out.println("Compilation Failed");
}
Edit
Can have a look at detailed example :
http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm

Related

Learning Java classes and methods, getting this error while testing my code [duplicate]

This question already has answers here:
What does "Could not find or load main class" mean?
(61 answers)
Closed 1 year ago.
I am following along with JAVA book for CS101 and trying to wrap my head around this exercise, but when I run my code, I keep getting this error
Error: Could not find or load main class Riddle
Caused by: java.lang.ClassNotFoundException: Riddle
JAVA CODE
public class Riddle{
private String question; //instance variables
private String answer;
public Riddle( String q, String a) //constructor
{
question = q;
answer = a;
}
public String getQuestion() //instance method
{
return question;
}
public String getAnswer()
{
return answer;
}
}
public class RiddleUser{
public static void main ( String argv [] ){
Riddle riddle1= new Riddle (
"What is black and white and red all over?",
"An embarrassed zebra.");
Riddle riddle2= new Riddle (
"What is black and white and read all over?",
"A newspaper." );
System.out.println("Here are two riddles:");
System.out.println(riddle1.getQuestion());
System.out.println(riddle2.getQuestion());
System.out.println("The answer to the first riddle is:");
System.out.println(riddle1.getAnswer());
System.out.println("The answer to the second riddle is:");
System.out.println(riddle2.getAnswer());
}
}
Here is the exercise I am doing, I also uploaded the PDF of the book, the exercise is on pages 71-73.
Basically, it wants to show you how to write a class and test it, If I am getting this correctly.
enter image description here
enter image description here
enter link description here
On a Java file, only 1 class can be public, the public class is the one with the main method.
The file and the public class must have the same name, RiddleUser.java in this case.
After declaring RiddleUser class in its own file.
This should work if you add private scope modifier to the RiddleUser class, without declaring it in its own file aswell.
Say your source path folder is ~/riddle-project/src/
riddle-project
└── src
├── Riddle.java
└── RiddleUser.java
Execute the following:
# compile main class
$ javac src/Riddle.java
# run main class with specified class path
$ java -classpath ./src/ Riddle
Class Path is the directory that contains the .class compiled java files

Can't find main(String[]) method in class: TapeDeck. The main method is in the other class which runs the program

I have two classes. When the I put class TapeDeckTestDrive first on the text editor, it runs fine. When I put the TestDrive class first, it gives the error that it can't find the main class. Why is this?
class TapeDeck {
boolean canRecord = false;
void playTape(){
System.out.println("tape playing");
}
void recordTape(){
System.out.println("tape recording");
}
}
class TapeDeckcTestDrive{
public static void main(String[] args){
TapeDeck t = new TapeDeck();
t.canRecord = true;
t.playTape();
if (t.canRecord == true) {
t.recordTape();
}
}
}
ERROR ON THIS FORMAT
VS
FOLLOWING WORKS FINE:
class TapeDeckcTestDrive{
public static void main(String[] args){
TapeDeck t = new TapeDeck();
t.canRecord = true;
t.playTape();
if (t.canRecord == true) {
t.recordTape();
}
}
}
class TapeDeck {
boolean canRecord = false;
void playTape(){
System.out.println("tape playing");
}
void recordTape(){
System.out.println("tape recording");
}
}
After you compile the code using the command:
javac fileName.java
Run the java .class file by only specifying fileName without the .java extension
java fileName
if you use fileName.java it won't run the specific .class file; it will try to interpret the .java file. if you want to interpret a .java file then parent class must contain the main(String[]) method.
First, You have to compile the File by using javac.
Then, You have to Run the file.
Classname where main is written.
javac filename.java
java classname
You Can Run the java program in two ways.
Directly run the java program by
java example_program.java
In this type compilation and Execution happens at runtime. That is
Byte codes is generated and executed immediately(works as a interpreter)
So,You must use the superclass(Containing the main method) at first followed by other
compound classes.
Note:
No .class file will generate. That means, it will generate byte code internally and will execute. Programmer's cannot view the class file.
In Second type, First, you should compile,
javac example_program.java
It will generate the example_program.class . Then, Execute the class file using,
java example_program
Here, the order of writing classes doesn't impact. you can write the classes in any order. it will work fine.
I split it into two files and added public to the classes/methods as well as the boolean. Now the code runs.
In some JDK's , JVM looks after the entry point function first due to which it need to be written first then the rest of the code. As main function is our entry point function it must be written first.
Steps 1.
--You have to compile the File by using javac. Then, You have to Run the file.
--Classname where main is written.
-- javac filename.java
-- java classname
It causing error due to:-
class TapeDeck {
boolean canRecord = false;
void playTape(){
System.out.println("tape playing");
}
void recordTape(){
System.out.println("tape recording");
}
}
class TapeDeckcTestDrive{
public static void main(String[] args){
TapeDeck t = new TapeDeck();
t.canRecord = true;
t.playTape();
if (t.canRecord == true) {
t.recordTape();
}
}
}
--Your tapedeck class doesn't main (String[]).
I got your problem.
First of all, check your classpath that you have set in Environment Variables
Follow the following steps:
***Step 1: *** Right Click on This PC --> Advanced system settings --> Environment Variables
***Step 2: *** Edit the variable classpath and add a new path or edit your old path that you have set. The path should be: C:\Program Files\Java_Home\jdk..\lib;.;
Note: The "." is must after a semicolon (;).
***Step 3: *** Close the CMD and open it again.
***Step 4: *** Now compile your using javac command: javac FileName.java
***Step 5: *** Run your code using java command: java ClassName
And there you go...
Try to put "public static void main" class first and then other methods in your code. It will definitely work.

Can we call a python method from java? [duplicate]

This question already has answers here:
Calling Python in Java?
(12 answers)
Closed 9 years ago.
I know jython allows us to call a java method from any java's classfile as if they were written for python, but is the reverse possible ???
I already have so many algorithms that written in python, they work pretty well with python and jython but they lack a proper GUI. I am planing to bring the GUI with the java and to keep the python library intact. I am not able to write a good GUI with jython or python and I cannot write a good algorithm with python. So the solution I found was to merge java's GUI and python's library. Is this possible. Can I call python's library from java.
Yes, that can be done . Normally this will be done by creating a PythonInterpreter object and then calling the python class using that .
Consider the following example :
Java :
import org.python.core.PyInstance;
import org.python.util.PythonInterpreter;
public class InterpreterExample
{
PythonInterpreter interpreter = null;
public InterpreterExample()
{
PythonInterpreter.initialize(System.getProperties(),
System.getProperties(), new String[0]);
this.interpreter = new PythonInterpreter();
}
void execfile( final String fileName )
{
this.interpreter.execfile(fileName);
}
PyInstance createClass( final String className, final String opts )
{
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
public static void main( String gargs[] )
{
InterpreterExample ie = new InterpreterExample();
ie.execfile("hello.py");
PyInstance hello = ie.createClass("Hello", "None");
hello.invoke("run");
}
}
Python :
class Hello:
__gui = None
def __init__(self, gui):
self.__gui = gui
def run(self):
print 'Hello world!'

How do I call java code from a Matlab program

I would like to calling my own Java program from Matlab.
This is my java program:
public class TestArgu{
public static void main(String[] args){
System.out.println("Test passing arguments!");
}
public void addNumber(int aNumber){
ansNumber = aNumber+5;
chk = aNumber;
System.out.println("input number = " + chk + ".\n");
System.out.println("ans = " + ansNumber + ".\n");
}
public int ansChk(){
return ansNumber;
}
private int ansNumber;
private int chk;
}
I did step by step from this link
http://www.mathworks.nl/support/solutions/en/data/1-URS0E/?...1...
but it is not working with my program.
I'm running Matlab program from the Server computer.
So I cannot edit the classpath.txt.
How to fix this problem?
First, delete the main function from your class. Then add the line
package mypackage.release;
before your class definition. Then compile it using the command
javac -verbose -cp /home/javaclasses -d /home/javaclasses /home/javasource/TestArgu.java
In matlab type
javaaddpath('/home/javaclasses');
clear java;
import mypackage.release.*;
test=TestArgu;
test.addNumber(6);
test.ansChk();
Remember that everytime you make changes and compile the java class, you must call clear java in matlab before the changes are available. This also has the unfortunate side effect of clearing all the variables in your workspace so make sure you don't have anything important to save before calling it.

Use java in matlab

I encountered a problem when I tried to use java from matlab. I read through the tutorials from MathWork.com several times, also I re-installed the JDK1.6, in order to be compatible with matlab. However, after my work, it still doesn't work...
Here is the contents in classpath.txt:
C:\Program Files\MATLAB\R2010a\java\jarext\xstream.jar
C:\Program Files\MATLAB\R2010a\toolbox\javabuilder\jar\win64 \javabuilder.jar
DYNAMIC JAVA PATH
C:\Users\Gao\Desktop\connected_components_labeling
Clearly, the directory is included in the file.
The connected_component_labeling is just a folder on my disk. The classes that I want to use in the connected_components_labeling are: Disjoint_Set.class and Node.class are in the connected_components_labeling folder.
I tried:
x = Disjoint_Set();
also
x = connected_components_labeling.Disjoint_Set();
None of them work. The only feedback I got from matlab is:
??? Undefined variable "connected_components_labeling" or class
"connected_components_labeling.Disjoint_Set".
I'm pretty frustrated. Could anyone help me out? I'd appreciate it. Thanks a ton!
Make sure that you are compiling the java files using a JRE/JDK that MATLAB is compatible with. As far as I can tell, MATLAB does not work properly with Java 7, so stick with Java 6 for the moment...
There are a couple of environment variables that affect MATLAB. In my case I have:
JAVA_HOME = C:\Program Files\Java\jdk1.6.0_32
MATLAB_JAVA = C:\Program Files\Java\jre6
PATH = ...;C:\Program Files\Java\jdk1.6.0_32\bin
Here is a simple test I just did:
C:\work\Student.java
public class Student {
private String name;
public Student(String str) {
name = str;
}
public void setName(String str) {
name = str;
}
public String getName() {
return name;
}
public static void main(String args[]) {
Student s = new Student("amro");
s.setName("unknown");
System.out.println("Hello " + s.getName());
}
}
I compile: javac Student.java (the output is placed in the same directory c:\work\Student.class). Now I test it from MATLAB:
javaaddpath('C:\work')
javaMethod('main','Student','')
s = Student('me')
char( s.getName() )
I get:
Hello unknown
s =
Student#8d6877
ans =
me

Categories