Coverting string to java code - java

I have a string constructed at run time like
str = "a+dataValue(i)";
where 'a' is a variable, 'dataValue(i)' is a function with argument i
Now I have a function where I want to use string str as part of code. For example
public void func()
{
for(int i=0;i<n;i++)
Sytem.out.println(converted_to_java_source(str)); //(i.e.) a+dataValue(i); it should be converted at runtime not compile time
}
I need output like as follows:
when a = 2; dataValue(i) returns i; n = 5
On call to func it should print
2 3 4 5 6 7
Thank you.

You are looking for the Java equivalent of the eval function / method in dynamically typed languages like JavaScript, Perl, Python and so on. Unfortunately there isn't one.
There are various ways to do this kind of thing in Java, but they are all expensive, and come with a variety of other down-sides.
My advice is to look for another (easier / cheaper) way to meet your requirement.
If you really need to go down the eval route, then here are some related Q/A's which give a reasonable coverage of the options.:
Is there an eval() function in Java?
Is there a java equivalent of the python eval function?

You could take a look at the Byte Code Engineering Libraray (BCEL) or ASM. In either case, things can get messy and overcomplicated so I would recommend what Stephen suggested and try to look for another way.
You could, for instance, use som if else statements to call your function in the usual manner, maybe something like:
String functionName = "...";
if (functionName.toLowerCase().equals("someMethodName")
{
someMethodName(someParams);
}

Related

How to calculate the time complexity when you use an API method?

I am learning how to calculate the time and space complexity recently. I know how to calculate the basic one. However, when it involves some pre-built method, I got confused. For example, the code below uses the indexOf() method in the String class, how do I calculate? Thanks!
class Solution {
public String longestCommonPrefix(String[] strs) {
String prefix = strs[0];
for(int i = 1; i < strs.length; i ++){
while(strs[i].indexOf(prefix) != 0){
prefix = prefix.substring(0,prefix.length()-1);
}
}return prefix;
}
}
As written in comments, this existing answer suggests:
There is nothing like time complexity of a program. We calculate time complexity for algorithms or, in the context of programming, for individual (atomic) functions.
But to answer the implicit "how to go about this in an interview?":
In the above example, understand that there are the explicit loops. If you focus on that, you can estimate how many times the inner loop body gets executed
From there, you could "mentally" inline that library call
Leading to: you would suggest to inspect the source code of the library methods to understand its runtime cost

C# .Take() in Java

I'm a C# Developer and recently starting get into Java development and here I have a question. Did Java have any build in method that doing the same thing with C# .Take()?
C# example:
int diffNo = 1;
someNumber.OrderBy(x => x.someNumber).Take(diffNo).ToList();
Java example:
someNumber.stream().sorted(Comparator.comparing(Object::getSomeNumber)).collect(Collectors.toList());
So now for Java part I only able to do sorting but don't know is there method can use to replace .Take()
Streams have a limit method, used to truncate a stream to up to the number of elements you provide as an argument.
So, assuming diffNo is a number, you can call it like this
someNumber.stream()
.sorted(Comparator.comparing(SomeClass::getSomeNumber))
.limit(diffNo)
.collect(Collectors.toList());

Build code by using Concatenation?

Is there a way i can create code build code by using Concatenation in Android studio/eclipse?
In other words i have 2 sets of strings one for each country i am dealing with ZA and KE. They have 2 different EULA's.
So i would like to pull the string related to the respective country.
String message = mContext.getString(R.string.eula_string_za);
above is an example of the output code. is there someway i can go about "creating" that based on If statements?
String str = "mContext.getString(R.string.eula_string_";
if (something = "ZA") {
str += "za);";
} else {
str += "ke);";
}
so if the country selected is ZA then the output code should be
mContext.getString(R.string.eula_string_za);
and if its KE it should be
mContext.getString(R.string.eula_string_ke);
and then the result will then pull the correct string from strings.xml?
Java is a compiled code, not an executed one,you can't write code this way like in an interpreted language.
The best way to manage different languages in android is to use a string.xml file for each language.
Take a look at this tutorial, it will help you a lot :
Supporting different languages in android
If you want to go this route you could try to use reflection. Have a look at Class.getField(…) if you want to use reflection.
Instead of first building a code string using a if statement you can also use the same if statement to find the correct string:
String str;
if (something.equals("ZA")) {
str = mContext.getString(R.string.eula_string_za);
} else {
str = mContext.getString(R.string.eula_string_ke);
}
Note that your condition something = "ZA" does not do what you think it does: It assigns something the string "ZA" and then evaluates itself to "ZA", so this would not even compile. The correct way would be something == "ZA", but even this does not work in the general case. You need to use String.equals(…). Some even argue you should use it the other way around (i.e. "ZA".equals(something)) to avoid a NullPointerException…
Another possibility would be to first build a Map from county to the corresponding string ID for all the EULAs you have and then asking the Map to return the correct one.
But probably the cleanest solution would be to use Androids built in mechanism, as hkN suggests.

Parsing C source file

If i have a C source file and i want to locate a specific local variable within a function and make it global - so another tool is able to process the C file (a tool i didn't write) what would be the easiest way to do this? I was thinking of using regex, but even that posses it's own problems. It's kind of like writing a mini C parser in Java.. a lot of work :S
Are there any libraries that can help make this easier?
For example, say i want to make the variable "i" into a global variable. The user will specify the function name and the variable name (but not the type the variable is - ie. "int").
I can use regex to find the function - sure. But from there i really don't know what the best approach would be?... Will CDT plugin help?
Example:
/*
* add.c
* a simple C program
*
*/
#include <stdio.h>
#define LAST 10
int main()
{
int i = 0;
int sum = 0;
for ( i = 1; i <= LAST; i++ ) {
sum += i;
} /*-for-*/
printf("sum = %d\n", sum);
return 0;
}
converted to:
/*
* add.c
* a simple C program
*
*/
#include <stdio.h>
#define LAST 10
int i = 0;
int main()
{
int sum = 0;
for ( i = 1; i <= LAST; i++ ) {
sum += i;
} /*-for-*/
printf("sum = %d\n", sum);
return 0;
}
If you do only trivial examples, you can hack this with Perl or some java regex. It won't work reliably on complex programs, because you need a real parser.
Our DMS Software Reengineering Toolkit and its C Front End could be used to to this pretty reliably.
DMS provides general purpose program analysis and transformation capability, parameterized by a programming langauge description. DMS's C Front explains to DMS what the precise syntax is for C (for a variety of dialects of C, including GCC and MS); it in effect provides a complete parser, producing Abstract Syntax trees (and the inverse: a C code generator from the ASTs) This allows DMS to read C source files accurately, including preprocessing.
With the parsed code in AST form, you can build DMS functions and/or write patterns to find function definitions and in particular your targeted variable. DMS code or alteratevely source-to-source transforms can then be used to either lift the variable out of the function, and/or insert code to track state changes of that variable so it can be seen.
So, with DMS and some custom code, you can achieve your desired effect. The example you provided is probably pretty simple to do with DMS, but the learning curve will stil be a lot; DMS is complex because the langauges it handles are complex, and you have to learn how to use it. So, this isn't an afternoon's exercise for a newbie.
Note: you will want to do this to preprocessed programs (otherwise you won't be generally able to parse them reliably). So, this should be something you do just before compilation, and shouldn't become part of the finalized code.
If you want to make permanent code changes, you'll need to parse the unpreprocessed code; that's a heckuva lot harder. DMS's C front end can do this to the extent the preprocessor directives are "structured"; about 95% of them are. So now you have a new problem: either fix the unstructured ones (a one time manual change), or reject files that can't be parsed with "tough luck".
You might use GCC instead of DMS; after all it has a very well tested C parser. It won't help you generate modified C code, though. Another alternative is Clang, which is coming up fast as a pretty good alternative. I think it will parse C++; not so sure about C or in particular the dialect of C your end user may be using (you didn't say). It has ASTs like DMS, and a kind of scheme for generating "patches" to code that might work.
The first thing I would demand is a complete specification of exactly when this is required and why, and how to identify when it is safe to do so without adversely affecting the program semantics. This is a really bad idea. Clearly those who gave you the assignment have no idea of either the implementation complexity, which is immense, or the adverse semantic effects. I am guessing that they will therefore be unable to come up with an adequate specification either, which will ultimately let you out.
I would also draw their attention to this discussion, especially Ira Baxter's comments. I used to build compilers for a living. It is not a task to learn, or ask about, on a forum.
Even if you are able to come up with a way to make such transformations, I think it's not a good idea. The program will not stay the same since you move around construction and destruction. Also, not all types are default constructable or copyable so in general the transformation is not possible.
Are you interested only in a few simple types? Then make that a part of the solution. Is the original code generated? Else, how can you trust to identify local objects by name only? The same name May also be used for different type of objects.

Is there a Java equivalent of Python's printf hash replacement?

Specifically I am converting a python script into a java helper method. Here is a snippet (slightly modified for simplicity).
# hash of values
vals = {}
vals['a'] = 'a'
vals['b'] = 'b'
vals['1'] = 1
output = sys.stdout
file = open(filename).read()
print >>output, file % vals,
So in the file there are %(a), %(b), %(1) etc that I want substituted with the hash keys. I perused the API but couldn't find anything. Did I miss it or does something like this not exist in the Java API?
You can't do this directly without some additional templating library. I recommend StringTemplate. Very lightweight, easy to use, and very optimized and robust.
I doubt you'll find a pure Java solution that'll do exactly what you want out of the box.
With this in mind, the best answer depends on the complexity and variety of Python formatting strings that appear in your file:
If they're simple and not varied, the easiest way might be to code something up yourself.
If the opposite is true, one way to get the result you want with little work is by embedding Jython into your Java program. This will enable you to use Python's string formatting operator (%) directly. What's more, you'll be able to give it a Java Map as if it were a Python dictionary (vals in your code).

Categories

Resources