Suppose I want to send following parameters :
key1: value1,
key2: value2
But currently I can't decide what will be there at place of key1,key2
That may be any string. key1 may be city,key2 may be code. Or key 1 may be companyName and key 2 is domain. So how can I set any custom unknown parametrs in method of java? Consider that I know total number of parameters and data type of their values, but can't determine their exact keys now. How to implement it in java?
You can send an array of objects in your method:
Object[] myObjects = new Object[2];
myObjects[0] = "This is a string";
myObjects[1] = 5;
myMethod(myObjects);
public void myMethod(Object[] myObjects){
// DoSomethingOverHere
}
If you only have Strings you can do the same but specify an array of Strings instead of objects. If you use objects, make sure to check the instance of the objects before using it.
I assume what you mean to achieve is a method that can accept any type of argument and still do the work.
Below is the approach I would use:
Lets say you want to use myMethod:
class MainClass {
public Object myMethod(Object A,Object B)
{
Object C=(Object) (A.toString()+","+B.toString());
System.out.println(C.toString());
return C;
}
}
And you can call it with any type of parameters:
public class TesterClass {
MainClass mainClass=new MainClass();
mainClass.myMethod(123, "PQR");
mainClass.myMethod(123.00, "PQR");
mainClass.myMethod(123.00, 123);
mainClass.myMethod(new int[]{1,2,3}, "PQR");
}
Your output will be:
123,PQR
123.0,PQR
123.0,123
[I#659e0bfd,PQR
last one is array, you can manipulate its processing)
Related
I have a class named MyVisitor that extends another class named Value. In one of my methods in MyVisitor, I have to store an array of Values in a HashMap. However, since the MyVisitor only extends Value, I can't return Value[ ] in the HashMap. Due to my limited knowledge on Java this is the solution I found:
In my Value class, I have:
public static int x;
public static Value ARRAY = new Value(new Object[x]); // I assume this would return an array of Objects of size x?
public Object[] objArray(){
return (Object[])value;
}
In MyVisitor class, I have this HashMap:
public Map<String, Value> array_memory = new HashMap<String, Value>();
In MyVisitor class, I have a method named array that uses Value.ARRAY like so:
Value.x = x; //Would change the value of public static int x in class Value
return array_memory.put(id, Value.ARRAY);
I have another method named arrayDec that calls array and does the following:
array(ctx);
String key = ctx.ID().getText();
Object[] val = array_memory.get(key).objArray();
System.out.println(val.length);
val.length prints 0
I have the following question:
Does = new Value(new Object[Value.x]); actually create an array of Objects of size x and masks it as Value?
Also, does Value.ARRAY actually return an array of Objects of size x?
Why does val.length return 0?
Confused? yeah me too :(
Also, if you're wondering why I'm doing this, I have a project in one of my courses that requires us to create our own compiler/interpreter. I'm trying to implement arrays. I'm using antlr4 to help me with it (thus the ctx.ID().getText() in one of the snippets there)
Any help would be appreciated. And if you have a better idea of how I should implement this I'm open to suggestions. Or if you know any links about implementing arrays in antlr4 that would be awesome as well. Thanks!
No. It creates an instance of Value. This instance might hold an array of Object if you have defined a constructor that takes an Object array as a parameter and assign that parameter to a member.
No. It returns an instance of Value
Impossible to say. Your code doesn’t explain how the member ‘value’ is defined or assigned.
I created an arrayList of type String in the class Demo as follows:
protected ArrayList<String> stringList;
public Demo()
{
stringList = new ArrayList<String>();
}
In the other class called client, I created an object of class Demo, so I can access the arrayList:
Demo d;
public Client()
{
b = new Demo();
}
another method called send message which exists in the Client class requires a parameters of type String. I invoked the send message and I gave the string arrayList as a parameters parameter but I keep getting an error as the type of the parameter is not a String.
sendMessage(b.stringList );
So, is there a way of storing the arrayList elements into String variables so they can be used within the sendMessage method.
Try to call toString method on your list to pass array list as a string.
So instead of:
sendMessage(b.stringList );
Use:
sendMessage(b.stringList.toString());
By doing so, you are creating a new String object everytime (taking a snapshot of whatever is there in list at that point of time) when you try to call sendMessage api and would not reflect any changes that you would do in your String list post passing on that string object to sendMessage api until you call sendMessage again.
It sounds like you want to call sendMessage() on each element of b.stringList, but you should clarify this. In that case, you can iterate through:
for (String element : b.stringList) {
sendMessage(element);
}
Or, on Java 8, simply
b.stringList.forEach(this::sendMessage); // Assuming sendMessage is a method of 'this'.
If you want a string representation of the list, an ArrayList does have a toString method, but if you want compatibility with Lists in general, write your own method to convert to a String, use a library or use new ArrayList<>(yourList).toString() (not recommended, as you must create new objects).
As we know variables are of different data types, but which data type are their names of?
As it seems they are String, but if they are String then this should be allowed:
int i=6;
String [] arr+i;
...as we can add an int to a String.
So if these are not String then what are they?
And if we want to create variable names dynamically how can we create it?
By dynamically I mean whenever the user clicks on a specific JComponent, a new variable is created, like:
int i=0;
//on first click
String str+i; ///str0
i++;
///on 2nd click
String str+i; ////str1
///i++;
How can I do it?
You can not create dynamic variables in Java because Java isn't a scripting language. YOu need to create variables in source code. But Java provides other ways to do this.
You can use arrays or Map<String, String> etc for this purpose.
Map<String, String> map= new HashMap<>();
int i=0;
while(true) {
// you can use whatever condition you need
details.put("key" + i, "val: "+i);
i++
// some condition to break the loop
}
Java identifiers are not of any type and definitely not String. You can't do this in java, instead, you use a data structure to use these values like ArrayList<String>and store the nth String in the nth index of the data structure like so:
ArrayList<String> strings= new ArrayList<String>(); // Create a new empty List
strings.add(index, string); //add string at index position of the List; can be replaced with strings.add(string) if the strings are being sequentially added
CONSIDER THIS:
public class Test {
public Test() {
}
public static void main(String[] args) {
// GenericType<Integer> intObj;//creates a generic type for integers
//String type
GenericType<String> strObj=new GenericType<String>("My data");
System.out.println("Value is " +strObj.getValue());
}
}
class GenericType<GT>{
GT obT;
GenericType(GT o){
obT=o;
}
GT getValue(){
return obT;
}
void showType(){
System.out.println("Type of GT is " +obT.getClass().getName());
}
}
GT is the name of a type parameter. This name is used as a placeholder for the actual type that will be passed to GenericType when an object is created. Thus, GT is used within GenericType whenever the type parameter is needed. Notice that GT is contained within
< >. This syntax can be generalized. Whenever a type parameter is being declared, it is specified within angle brackets. Because Gen uses a type parameter, Gen is a generic class, which is also called a parameterized type.
as mentioned above JAVA provide you with advanced generic classes such as ArrayList, Vectors, Hashmaps to cater for such scenarios .
previous thread similar: How to create new variable in java dynamically
Variable names do not have data types. They are merely references. They are not a String, they are not an int, they are just names. You can't dynamically declare a variable with a name derived from the name of another variable, Java does not work this way.
Java does not work this way. Other languages do but Java isn't one of them. You can't dynamically manipulate the names of variables because they are fixed at compile time. However, in some interpreted scripting languages such a thing is possible.
To be more accurate if they are fixed to be anything at all they are fixed at compile time. If java is not compiled in debug mode the names of the variables cease to be at all. They just become addresses of memory locations.
See this for details: Can I get information about the local variables using Java reflection?
Firstly variables can be categorized into two. primitives (standard ) types such as int, float,double, char,boolean, byte... and non-primitives(user defined)types such as String, Integer, Float, Double. String type fall under non primitive , its a class provided by java.lang Api such that when you create a string variable you are indeed creating an object EX String str; str is an object it can as well be declared as String str=new String();
hence the string class consist of helper methods that may help to achieve your objective, you can as well use concatenation/joining of strings as follows:
class Demo{
String str;
static int i;
JButton but=new JButton("click me!");
.....
public static void actionPeaformed(ActionEvent e){
Object source=e.getSource();
str="msg";
if(source==but){
String newStr;
newStr=str+i;
System.out.println(newStr);
}
}
}
where str may contain some message/text eg from label/elsewhere for every click
I would like to write a function that would enable me to do the following
inputs: variable number of objects of any type
output: a string that would be NameObj1=ValueObj1, ..., NameObjN=ValueObjN
All objects I would pass to the function would have a toString() method.
Example:
double x=1.1; int y=2; ClassA a
theFunction(x,y,a)
=> this would output "x=1.1, y=1, a=[whatever a.toString() output]"
Is that possible ?
here's something close:
you can write a var-arg function like so:
public static String describeArguments (Object... arguments) {
StringBuilder output = new StringBuilder();
int counter = 1;
for (Object argument : arguments) {
output.append("object #").append(counter++).append(": ").append(argument.toString());
}
return output.toString();
}
strictly speaking method arguments dont have names. you could retrieve the argument parameter name using reflection if the symbol tables werent stripped out #compile time, but its brutish and ugly.
There's no way of getting what you wrote to be the "name" of a variable, because the only way of referencing it, is by itself, and by value is not possible as well.
As mentioned in other answers and comments there is no "name of an object". But if the objects you are interested in are all fields of one class, you could write a function that uses reflection to access that objects fields and prints their names.
Take a look at the reflection tutorial. There is also an example that is very close to what you might have in mind.
You can create a map like
Map<String,Object> map= new HashMap<String,Object>();
map.put("x", 1.1);
map.put("y",2);
map.put("a", MyClass.class);
And call theFunction(map), where theFunction is:
public void theFunction(HashMap<String,Object> list) {
StringBuilder sb = new StringBuilder();
for(String key:list.keySet()) {
try {
Object currentObject = list.get(key);
sb.append(key+"="+currentObject.getClass().getMethod("toString").invoke(currentObject)+" ");
}
catch(Exception e){}
}
System.out.println(sb.toString());
}
I need to pass arguments to a java method func(String, String...).
Problem is I have all the strings I need to pass as arguments, but they are in an ArrayList container.
For Example:
for(...some condition...)
{
//the other method returns an ArrayList with different size in each iteration
ArrayList <String> values = someOtherMethod();
func(values) //values is an ArrayList<String>, containing all the arguments
}
I get an error saying that ArrayList<String> can't be converted to String.
The size of values changes, because the someOtherMethod method returns a container with different size each iteration, so I can't pass values[0], values[1], etc as arguments.
I'm guessing the func wants an X amount of String variables, but I don't know how to convert a container to an X amount of variables when the size of the container isn't constant.
The "..." operator accepts arrays, so you could just do the following:
ArrayList <String> values = someOtherMethod();
func(values.toArray(new String[values.size()]);
It's a little bit complex as func requires one String and then an arbitrary number of additional Strings:
List<String> values = someOtherMethod();
if (values.isEmpty()) {
// handle special case
} else{
func(values.get(0), values.subList(1, values.size()).toArray(new String[]));
}
I'm guessing the func wants an X amount of String variables,
I guess you are looking for Varargs.
Change your function signature to accept as
public someReturnType func(String... vargs) { }
Which takes variable length of args as parameter.
And then inside the method ,you can access them like
for (String currentarg: args) {
// do something with currentarg
}
As a side note : Available from version 1.5 only.
Learn more from docs about Varargs