Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

how to execute a statement

  Asked By: Caleb    Date: Feb 09    Category: Java    Views: 914
  

I have an executable statement in the form of a string
, such as

int x =0 ;
String str = "System.out.println(x); "

How can i execute it ???

I tried using RunTimeInterface but it didnt help
because the exec command is useful only for system
calls.

Share: 

 

5 Answers Found

 
Answer #1    Answered By: Mike Stephens     Answered On: Feb 09

Your syntax is incorrect. Here is an example, that might help.


// Demonstrates the System.out.println

public class example

{
public static void main(String[] args)
{
int x =0 ;

System.out.println(x);
System.out.println("System.out.println");
System.out.println("See the difference?");

}
}

 
Answer #2    Answered By: Adalric Fischer     Answered On: Feb 09

you maybe want to write "System.out.println(x);" with parametric x values..

public static void main(String[] args)
{
int x;
String str;

for (x=0; x<5; x++) {
str = "System.out.println("+x+");";
System.out.println(str);
}
}

 
Answer #3    Answered By: Julia Flores     Answered On: Feb 09

What I think you are saying is that you want to dynamically create a
variable at runtime of type int and maybe even give it a value. You can not
extend the members of a class or method at runtime like that, however if you
need to assign a value to a variable and you don't know the type until the
program is running then assign it an object to start with and at runtime
convert the object to the appropriate datatype on the fly.

//Design time Example.

Object unknownType = null;

//Runtime example:

int = ((Integer) unknownType).intValue;

 
Answer #4    Answered By: Jarvia Miller     Answered On: Feb 09

It seems i was not clear in putting my question :
This is what i want to do

Firstly, the string  i have is not a static string.
I need to write data to a buffer. The data can be
anything. I have a class which returns me two vectors
say V1 and V2.

V1 = ".Int" // just for this example
V2 = "index" // index is the name of that int
variable.

Now i construct this string in my program.

String str = "buffer.write" + V1 + "(" + V2 +");"

and now i want to execute  this statement  , which i
have in the form  String str.Here buffer is an
instance of ByteBuffer.

 
Answer #5    Answered By: Allan Bailey     Answered On: Feb 09

You can try with Reflection...........

 
Didn't find what you were looking for? Find more on how to execute a statement Or get search suggestion and latest updates.




Tagged: