Trikaldarshi Trikaldarshi - 5 days ago 6
Android Question

Can I execute a String something like a language command?

Example---
Like for SQL we write SQL statement as String and then we execute

strsql = "Select * from international_table ";


now what we do we execute this statement
similarly

I want in java or c#

like this

strjavacode = "String str = \" Masdfksdja \";System.out.Println(str); "


and after that some how to execute this

I'm eager to do something like this in which I will not have to declare variable and assign values
or statement several times.

Answer

Depends what you want. If after the execution you want s1 and s100 to be available for further use then this is no at all possible. Nor is it possible to write arbitrary code that can access any non-global variables.

What you can do is write a class that implements an interface and compile that class at runtime. You can then instantiate an instance of this new class using reflections. You can query this object before, during and after execution if the interface provides appropriate methods. You could also use reflections to gain access to the fields of the object as well.

This is all very hacky though, and trying to accomplish things in a way Java is not suited for. If you just want to create 100 arbitrary strings then it's probably better to use an array and create your own small DSL to accomplish simply tasks.

One last method you may wish to try is to use scripting languages that run on the JVM such as Jython or Groovy. Groovy is great for this. Since Groovy is a superset of Java you don't have to worry about valid Java not compiling. Though what might be of concern is that invalid Java might compile. eg String s = 'some string' is valid Groovy, but not valid Java.

Using Groovy you could do something like:

import groovy.lang.GroovyShell;

public class SomeClass {

    public static void main(String[] args) {
        GroovyShell shell = new GroovyShell();

        for (String arg : args) {
            Object result = shell.evaluate(arg);

            System.out.println("result is: "+result);
        }
    }

}

For this you could have input args of say String s1 = "hello";, String s2 = "world"; and String combined = s1 + " " + s2;.