Execute Java method with parameters from String - java

I am trying to create a way to give a full method call as a string to a function, which then should try to actually call this method.
This should work with any type and any number and generally arbitrary parameters.
The class where the methods are declared is going to be fixed (probably given as an argument to this classes constructor)
Basically it should work, as if the contents of the String (whatever they might be) would be a line inside the function.
Obviously this function can only try to do this and would need to catch and handle all exceptions (eg. when that method doesn't exist in the given class).
Like this:
public class Thisclass{
String example = "Testmethod(1, 4.23, 'test')";
Class otherclass;
public void Thisclass(Class implementationClass){
this.otherclass = implementationClass;
}
//Calling myFunction like this: myFunction(example);
//Should result in this being called: otherclass.Testmethod(1, 4.23, "test");
public void myFunction(String input){
try{
//Something here
}
catch(Exception ex){
//Handle exceptions
}
}
}
I know how I could do this when I knew the number, type and order of the parameters using reflection, but can I do the same with an unknown number of parameters of unknown type and in an unknown order?
I would be ok with limiting the maximum total number of parameters to something relatively small (eg. 4 or 5), but I would like to leave the type and order of the parameters relatively unlimited.
It would also be ok to limit the types to something like int, float, double, char and String plus arrays of all these.
I know I could overload a method with all sorts of possible parameters, but that is very unpractical, as only allowing a maximum of 4 integers or integer arrays would already bring me up to 8 different versions and allowing a random mix of those two would already need 31 different implementations...
Is this even possible?
Edit:
The comments tell me, that some of you don't really understand what I want to do.
Basically I am parsing a HTML file to be rendered using opengl and I want to be able to make links or buttons in the HTML file execute some method, but I do not want to specify one method, but leave the methods to a different part of the project.
Think:Run Method where MyMethod can be an arbitrary Method. The only thing that is known about the method is that it is implemented in the class otherclass. After parsing the HTML I can get the value of the href attribute as a string, so basically "MyMethod(1, 4.23, 'test')".
For those that suggested that it would be easiest to create / copy a method for every possible combination and order of the data types mentioned above: I did a quick calculation and only accepting 1-4 parameters of the 5 types mentioned above in an arbitrary combination and order, would require over a million different versions of the method. I really doubt that creating all those and somehow not ending with missing or doubled methods at the end is faster than anything else.
The best suggestion so far is the one from saka1029, to basically create an all new java file and compile it using the compiler api and then to run it. I will look into that, as it seems to be the best idea so far.

Related

Is it bad practice in Java to modify input object in void method?

In Java, assume you have a data object object with an attribute bar that you need to set with a value that is returned from a complex operation done in an external source. Assume you have a method sendRequestToExternalSource that send a request based on 'object' to the external source and gets an object back holding (among other things) the needed value.
Which one of these ways to set the value is the better practice?
void main(MyObject object) {
bar = sendRequestToExternalSource(object);
object.setBar(bar);
}
String sendRequestToExternalSource(MyObject object) {
// Send request to external source
Object response = postToExternalSource(object);
//Do some validation and logic based on response
...
//Return only the attribute we are interested in
return response.getBar();
}
or
void main(MyObject object) {
sendRequestToExternalSourceAndUpdateObject(object);
}
void sendRequestToExternalSourceAndUpdateObject(MyObject object) {
// Send request to external source
Object response = postToExternalSource(object);
//Do some validation and logic based on response
...
//Set the attribute on the input object
object.setBar(response.getBar());
}
I know they both work, but what is the best practice?
It depends on a specific scenario. Side-effects are not bad practice but there are also scenarios where a user simply won't expect them.
In any case your documentation of such a method should clearly state if you manipulate arguments. The user must be informed about that since it's his object that he passes to your method.
Note that there are various examples where side-effects intuitively are to be expected and that's also totally fine. For example Collections#sort (documentation):
List<Integer> list = ...
Collections.sort(list);
However if you write a method like intersection(Set, Set) then you would expect the result being a new Set, not for example the first one. But you can rephrase the name to intersect and use a structure like Set#intersect(Set). Then the user would expect a method with void as return type where the resulting Set is the Set the method was invoked on.
Another example would be Set#add. You would expect that the method inserts your element and not a copy of it. And that is also what it does. It would be confusing for people if it instead creates copies. They would need to call it differently then, like CloneSet or something like that.
In general I would tend to giving the advice to avoid manipulating arguments. Except if side-effects are to be expected by the user, as seen in the example. Otherwise the risk is too high that you confuse the user and thus create nasty bugs.
I would choose the first one if I have only these two choices. And the reason of that is "S" in SOLID principles, single responsibility. I think the job of doComplicatedStuff method is not setting new or enriched value of bar to MyObject instance.
Of course I don't know use case that you are trying to implement, but I suggest looking at decorator pattern to modify MyObject instance
I personally prefer the variant barService.doComplicatedStuff(object); because I avoid making copies

Determine all Strings (dynamically built and literals) passed to a method in Java

I am trying to build a static code analysis, that allows to collect all Strings passed to a function without running the code. I am using Eclipse JDT (3.10.0) to parse the code.
Assumptions/Precodinditions:
Every passed argument can be resolved to a String literal
The value is not saved to any (non-static) fields and then passed on in another call
All callers can be identified and visited by the parser
The MethodInvocation of the examined method is already identified
What i have:
At the moment i am able to identify all MethodInvocations on that particular Method and therefore am able to collect all arguments passed as StringLiterals.
I am able to see all argument Types but, of course, cannot determine the value of parameters, fields, objects etc. as the value binding would only be available at runtime.
The Problem
Under the assumption, that every single passed Argument (no matter the Type) is at some time resolvable to a StringLiteral or a Concatenation of StringLiterals, i should be able to determine the distinct set of all Values which are passed to this method by the program.
Is there a way, to recursively determine the String value of all method calls without following every stacktrace and manually implementing the logic for every occurence?
Imagine the following examples:
public class IAmAnalysed{
public void analysedMethod(String argument){
//do something useful
}
}
//Values in a map
hashMap.put("test", "TestString");
hashMap.put("test2", "TestString2");
for (Map.Entry<String, String> e : hashMap.entrySet()) {
iAmAnalysed.analysedMethod(e.getValue);
}
//util method
public void util(String argument){
iAmAnalysed.analysedMethod(argument + "utilCalled");
}
util("TestString3")
This should give me the following set of values:
TestString
TestString2
TestString3utilCalled
The only appraoch i can think of (using Eclipse JDT) is to add every argument that is no StringLiteral to a working Set and start one more iteration with the ASTParser to determine where the passed value is set, or where it comes from. Then i add this location to the workingSet and iterate once more. This at the end should lead me to all possible arguments.
Unfortunately with this approach i would have to implement logic for every single possible way the value could be passed (imagine all the other possibilities next to the two above)
Examining all possible data flows into a given method is not generally feasible by static analysis. The approach you outline can work for a small group of programs, until you hit, e.g., recursion, at what point the thing will blow up.
Maybe a comprehensive test suite will give better results than static analysis on this one.

Java - Can someone explain me what are varargs doing in this piece of code? [duplicate]

I'm afraid of varargs. I don't know what to use them for.
Plus, it feels dangerous to let people pass as many arguments as they want.
What's an example of a context that would be a good place to use them?
Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String.format. The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.
String.format("This is an integer: %d", myInt);
String.format("This is an integer: %d and a string: %s", myInt, myString);
A good rule of thumb would be:
"Use varargs for any method (or constructor) that needs an array of T (whatever type T may be) as input".
That will make calls to these methods easier (no need to do new T[]{...}).
You could extend this rule to include methods with a List<T> argument, provided that this argument is for input only (ie, the list is not modified by the method).
Additionally, I would refrain from using f(Object... args) because its slips towards a programming way with unclear APIs.
In terms of examples, I have used it in DesignGridLayout, where I can add several JComponents in one call:
layout.row().grid(new JLabel("Label")).add(field1, field2, field3);
In the code above the add() method is defined as add(JComponent... components).
Finally, the implementation of such methods must take care of the fact that it may be called with an empty vararg! If you want to impose at least one argument, then you have to use an ugly trick such as:
void f(T arg1, T... args) {...}
I consider this trick ugly because the implementation of the method will be less straightforward than having just T... args in its arguments list.
Hopes this helps clarifying the point about varargs.
I use varargs frequently for outputting to the logs for purposes of debugging.
Pretty much every class in my app has a method debugPrint():
private void debugPrint(Object... msg) {
for (Object item : msg) System.out.print(item);
System.out.println();
}
Then, within methods of the class, I have calls like the following:
debugPrint("for assignment ", hwId, ", student ", studentId, ", question ",
serialNo, ", the grade is ", grade);
When I'm satisfied that my code is working, I comment out the code in the debugPrint() method so that the logs will not contain too much extraneous and unwanted information, but I can leave the individual calls to debugPrint() uncommented. Later, if I find a bug, I just uncomment the debugPrint() code, and all my calls to debugPrint() are reactivated.
Of course, I could just as easily eschew varargs and do the following instead:
private void debugPrint(String msg) {
System.out.println(msg);
}
debugPrint("for assignment " + hwId + ", student " + studentId + ", question "
+ serialNo + ", the grade is " + grade);
However, in this case, when I comment out the debugPrint() code, the server still has to go through the trouble of concatenating all the variables in every call to debugPrint(), even though nothing is done with the resulting string. If I use varargs, however, the server only has to put them in an array before it realizes that it doesn't need them. Lots of time is saved.
Varargs can be used when we are unsure about the number of arguments to be passed in a method. It creates an array of parameters of unspecified length in the background and such a parameter can be treated as an array in runtime.
If we have a method which is overloaded to accept different number of parameters, then instead of overloading the method different times, we can simply use varargs concept.
Also when the parameters' type is going to vary then using "Object...test" will simplify the code a lot.
For example:
public int calculate(int...list) {
int sum = 0;
for (int item : list) {
sum += item;
}
return sum;
}
Here indirectly an array of int type (list) is passed as parameter and is treated as an array in the code.
For a better understanding follow this link(it helped me a lot in understanding this concept clearly):
http://www.javadb.com/using-varargs-in-java
P.S: Even I was afraid of using varargs when I didn't knw abt it. But now I am used to it.
As it is said: "We cling to the known, afraid of the unknown", so just use it as much as you can and you too will start liking it :)
Varargs is the feature added in java version 1.5.
Why to use this?
What if, you don't know the number of arguments to pass for a method?
What if, you want to pass unlimited number of arguments to a method?
How this works?
It creates an array with the given arguments & passes the array to the method.
Example :
public class Solution {
public static void main(String[] args) {
add(5,7);
add(5,7,9);
}
public static void add(int... s){
System.out.println(s.length);
int sum=0;
for(int num:s)
sum=sum+num;
System.out.println("sum is "+sum );
}
}
Output :
2
sum is 12
3
sum is 21
I have a varargs-related fear, too:
If the caller passes in an explicit array to the method (as opposed to multiple parameters), you will receive a shared reference to that array.
If you need to store this array internally, you might want to clone it first to avoid the caller being able to change it later.
Object[] args = new Object[] { 1, 2, 3} ;
varArgMethod(args); // not varArgMethod(1,2,3);
args[2] = "something else"; // this could have unexpected side-effects
While this is not really different from passing in any kind of object whose state might change later, since the array is usually (in case of a call with multiple arguments instead of an array) a fresh one created by the compiler internally that you can safely use, this is certainly unexpected behaviour.
I use varargs frequently for constructors that can take some sort of filter object. For example, a large part of our system based on Hadoop is based on a Mapper that handles serialization and deserialization of items to JSON, and applies a number of processors that each take an item of content and either modify and return it, or return null to reject.
In Java doc of Var-Args it is quite clear the usage of var args:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
about usage it says:
"So when should you use varargs?
As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility.
As an API designer, you should use them sparingly, only when the benefit is truly compelling.
Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called. "

Generic methods returning dynamic object types

Possibly a question which has been asked before, but as usual the second you mention the word generic you get a thousand answers explaining type erasure. I went through that phase long ago and know now a lot about generics and their use, but this situation is a slightly more subtle one.
I have a container representing a cell of data in an spreadsheet, which actually stores the data in two formats: as a string for display, but also in another format, dependent on the data (stored as object). The cell also holds a transformer which converts between the type, and also does validity checks for type (e.g. an IntegerTransformer checks if the string is a valid integer, and if it is returns an Integer to store and vice versa).
The cell itself is not typed as I want to be able to change the format (e.g. change the secondary format to float instead of integer, or to raw string) without having to rebuild the cell object with a new type. a previous attempt did use generic types but unable to change the type once defined the coding got very bulky with a lot of reflection.
The question is: how do I get the data out of my Cell in a typed way? I experimented and found that using a generic type could be done with a method even though no constraint was defined
public class Cell {
private String stringVal;
private Object valVal;
private Transformer<?> trans;
private Class<?> valClass;
public String getStringVal(){
return stringVal;
}
public boolean setStringVal(){
//this not only set the value, but checks it with the transformer that it meets constraints and updates valVal too
}
public <T> T getValVal(){
return (T) valVal;
//This works, but I don't understand why
}
}
The bit that puts me off is: that is ? it can't be casting anything, there is no input of type T which constrains it to match anything, actually it doesn't really say anything anywhere. Having a return type of Object does nothing but give casting complications everywhere.
In my test I set a Double value, it stored the Double (as an object), and when i did Double testdou = testCell.getValVal(); it instantly worked, without even an unchecked cast warning. however, when i did String teststr = testCell.getValVal() I got a ClassCastException. Unsurprising really.
There are two views I see on this:
One: using an undefined Cast to seems to be nothing more than a bodge way to put the cast inside the method rather than outside after it returns. It is very neat from a user point of view, but the user of the method has to worry about using the right calls: all this is doing is hiding complex warnings and checks until runtime, but seems to work.
The second view is: I don't like this code: it isn't clean, it isn't the sort of code quality I normaly pride myself in writing. Code should be correct, not just working. Errors should be caught and handled, and anticipated, interfaces should be foolproof even if the only expecter user is myself, and I always prefer a flexible generic and reusable technique to an awkward one off. The problem is: is there any normal way to do this? Is this a sneaky way to achieve the typeless, all accepting ArrayList which returns whatever you want without casting? or is there something I'm missing here. Something tells me I shouldn't trust this code!
perhaps more of a philosophical question than I intended but I guess that's what I'm asking.
edit: further testing.
I tried the following two interesting snippets:
public <T> T getTypedElem() {
T output = (T) this.typedElem;
System.out.println(output.getClass());
return output;
}
public <T> T getTypedElem() {
T output = null;
try {
output = (T) this.typedElem;
System.out.println(output.getClass());
} catch (ClassCastException e) {
System.out.println("class cast caught");
return null;
}
return output;
}
When assigning a double to typedElem and trying to put it into a String I get an exception NOT on the cast to , but on the return, and the second snippet does not protect. The output from the getClass is java.lang.Double, suggesting that is being dynamically inferred from typedElem, but that compiler level type checks are just forced out of the way.
As a note for the debate: there is also a function for getting the valClass, meaning it's possible to do an assignability check at runtime.
Edit2: result
After thinking about the options I've gone with two solutions: one the lightweight solution, but annotated the function as #depreciated, and second the solution where you pass it the class you want to try to cast it as. this way it's a choice depending on the situation.
You could try type tokens:
public <T> T getValue(Class<T> cls) {
if (valVal == null) return null;
else {
if (cls.isInstance(valVal)) return cls.cast(valVal);
return null;
}
}
Note, that this does not do any conversion (i.e., you cannot use this method to extract a Double, if valVal is an instance of Float or Integer).
You should get, btw., a compiler warning about your definition of getValVal. This is, because the cast cannot be checked at run-time (Java generics work by "erasure", which essentially means, that the generic type parameters are forgotten after compilation), so the generated code is more like:
public Object getValVal() {
return valVal;
}
As you are discovering, there is a limit to what can be expressed using Java's type system, even with generics. Sometimes there are relationships between the types of certain values which you would like to assert using type declarations, but you can't (or perhaps you can, at the cost of excess complexity and long, verbose code). I think the sample code in this post (question and answers) is a good illustration of that.
In this case, the Java compiler could do more type checking if you stored the object/string representation inside the "transformer". (Perhaps you'll have to rethink what it is: maybe it's not just a "transformer".) Put a generic bound on your base Transformer class, and make that same bound the type of the "object".
As far as getting the value out of the cell, there's no way that compiler type checking will help you there, since the value can be of different types (and you don't know at compile time what type of object will be stored in a given cell).
I believe you could also do something similar to:
public <T> void setObject(Transformer<T> transformer, T object) {}
If the only way to set the transformer and object is through that method, compiler type checking on the arguments will prevent an incompatible transformer/object pair from going into a cell.
If I understand what you're doing, the type of Transformer which you use is determined solely by the type of object which the cell is holding, is that right? If so, rather than setting the transformer/object together, I would provide a setter for the object only, and do a hash lookup to find the appropriate transformer (using the object type as key). The hash lookup could be done every time the value is set, or when it is converted to a String. Either way would work.
This would naturally make it impossible for the wrong type of Transformer to be passed in.
I think you are a static-typed guy, but lemme try: have you thought about using a dynamic language like groovy for that part?
From your description it seems to me like types are more getting in the way than helping anything.
In groovy you can let the Cell.valVal be dynamic typed and get an easy transformation around:
class Cell {
String val
def valVal
}
def cell = new Cell(val:"10.0")
cell.valVal = cell.val as BigDecimal
BigDecimal valVal = cell.valVal
assert valVal.class == BigDecimal
assert valVal == 10.0
cell.val = "20"
cell.valVal = cell.val as Integer
Integer valVal2 = cell.valVal
assert valVal2.class == Integer
assert valVal2 == 20
Where as it's everything needed for the most common transformations. You can add yours too.
If needing to transform other blocks of code, note that java's syntax is valid groovy syntax, except for the do { ... } while() block

Should Java method arguments be used to return multiple values?

Since arguments sent to a method in Java point to the original data structures in the caller method, did its designers intend for them to used for returning multiple values, as is the norm in other languages like C ?
Or is this a hazardous misuse of Java's general property that variables are pointers ?
A long time ago I had a conversation with Ken Arnold (one time member of the Java team), this would have been at the first Java One conference probably, so 1996. He said that they were thinking of adding multiple return values so you could write something like:
x, y = foo();
The recommended way of doing it back then, and now, is to make a class that has multiple data members and return that instead.
Based on that, and other comments made by people who worked on Java, I would say the intent is/was that you return an instance of a class rather than modify the arguments that were passed in.
This is common practice (as is the desire by C programmers to modify the arguments... eventually they see the Java way of doing it usually. Just think of it as returning a struct. :-)
(Edit based on the following comment)
I am reading a file and generating two
arrays, of type String and int from
it, picking one element for both from
each line. I want to return both of
them to any function which calls it
which a file to split this way.
I think, if I am understanding you correctly, tht I would probably do soemthing like this:
// could go with the Pair idea from another post, but I personally don't like that way
class Line
{
// would use appropriate names
private final int intVal;
private final String stringVal;
public Line(final int iVal, final String sVal)
{
intVal = iVal;
stringVal = sVal;
}
public int getIntVal()
{
return (intVal);
}
public String getStringVal()
{
return (stringVal);
}
// equals/hashCode/etc... as appropriate
}
and then have your method like this:
public void foo(final File file, final List<Line> lines)
{
// add to the List.
}
and then call it like this:
{
final List<Line> lines;
lines = new ArrayList<Line>();
foo(file, lines);
}
In my opinion, if we're talking about a public method, you should create a separate class representing a return value. When you have a separate class:
it serves as an abstraction (i.e. a Point class instead of array of two longs)
each field has a name
can be made immutable
makes evolution of API much easier (i.e. what about returning 3 instead of 2 values, changing type of some field etc.)
I would always opt for returning a new instance, instead of actually modifying a value passed in. It seems much clearer to me and favors immutability.
On the other hand, if it is an internal method, I guess any of the following might be used:
an array (new Object[] { "str", longValue })
a list (Arrays.asList(...) returns immutable list)
pair/tuple class, such as this
static inner class, with public fields
Still, I would prefer the last option, equipped with a suitable constructor. That is especially true if you find yourself returning the same tuple from more than one place.
I do wish there was a Pair<E,F> class in JDK, mostly for this reason. There is Map<K,V>.Entry, but creating an instance was always a big pain.
Now I use com.google.common.collect.Maps.immutableEntry when I need a Pair
See this RFE launched back in 1999:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4222792
I don't think the intention was to ever allow it in the Java language, if you need to return multiple values you need to encapsulate them in an object.
Using languages like Scala however you can return tuples, see:
http://www.artima.com/scalazine/articles/steps.html
You can also use Generics in Java to return a pair of objects, but that's about it AFAIK.
EDIT: Tuples
Just to add some more on this. I've previously implemented a Pair in projects because of the lack within the JDK. Link to my implementation is here:
http://pbin.oogly.co.uk/listings/viewlistingdetail/5003504425055b47d857490ff73ab9
Note, there isn't a hashcode or equals on this, which should probably be added.
I also came across this whilst doing some research into this questions which provides tuple functionality:
http://javatuple.com/
It allows you to create Pair including other types of tuples.
You cannot truly return multiple values, but you can pass objects into a method and have the method mutate those values. That is perfectly legal. Note that you cannot pass an object in and have the object itself become a different object. That is:
private void myFunc(Object a) {
a = new Object();
}
will result in temporarily and locally changing the value of a, but this will not change the value of the caller, for example, from:
Object test = new Object();
myFunc(test);
After myFunc returns, you will have the old Object and not the new one.
Legal (and often discouraged) is something like this:
private void changeDate(final Date date) {
date.setTime(1234567890L);
}
I picked Date for a reason. This is a class that people widely agree should never have been mutable. The the method above will change the internal value of any Date object that you pass to it. This kind of code is legal when it is very clear that the method will mutate or configure or modify what is being passed in.
NOTE: Generally, it's said that a method should do one these things:
Return void and mutate its incoming objects (like Collections.sort()), or
Return some computation and don't mutate incoming objects at all (like Collections.min()), or
Return a "view" of the incoming object but do not modify the incoming object (like Collections.checkedList() or Collections.singleton())
Mutate one incoming object and return it (Collections doesn't have an example, but StringBuilder.append() is a good example).
Methods that mutate incoming objects and return a separate return value are often doing too many things.
There are certainly methods that modify an object passed in as a parameter (see java.io.Reader.read(byte[] buffer) as an example, but I have not seen parameters used as an alternative for a return value, especially with multiple parameters. It may technically work, but it is nonstandard.
It's not generally considered terribly good practice, but there are very occasional cases in the JDK where this is done. Look at the 'biasRet' parameter of View.getNextVisualPositionFrom() and related methods, for example: it's actually a one-dimensional array that gets filled with an "extra return value".
So why do this? Well, just to save you having to create an extra class definition for the "occasional extra return value". It's messy, inelegant, bad design, non-object-oriented, blah blah. And we've all done it from time to time...
Generally what Eddie said, but I'd add one more:
Mutate one of the incoming objects, and return a status code. This should generally only be used for arguments that are explicitly buffers, like Reader.read(char[] cbuf).
I had a Result object that cascades through a series of validating void methods as a method parameter. Each of these validating void methods would mutate the result parameter object to add the result of the validation.
But this is impossible to test because now I cannot stub the void method to return a stub value for the validation in the Result object.
So, from a testing perspective it appears that one should favor returning a object instead of mutating a method parameter.

Categories