Java parameter name to string

How can I get parameters name same as a parameter in java

I want instead of «value is mandatory», parameter name like «Name is namdatory» and «address is mandatory» should come.

Pass the name of the parameter as well, e.g. in an object that contains name and value. Then concatenate the name to the message, e.g. something like this Objects.requirNonNull(param.getValue(),param.getName() + » is mandatory»); .

If you’re after the method parameters’ names, it depends on your environment, e.g. whether your compiled code contains the names or not (AFAIK only available for Java 8+) — something like here: stackoverflow.com/questions/21455403/… . There are libraries that provide parameter names for lower Java versions by hooking into the build process if you can’t use Java 8. But in both cases you’d have to pass the names to validateParameters() since that method doesn’t know what is being passed.

Thanks,but i don’t want to make like key value pair. If I am passing address as a parameter then i want that parameter name in string format.

2 Answers 2

There is no such magic for the invoked method. Since you are passing values to the method, these arguments do not bear any information about their parameter roles. In fact, there is no guaranty that the values passed to validateParameters are parameters in the callers context. You can, e.g. invoke it as validateParameters(Math.sin(2), null) or validateParameters(bufferedReader.readLine()) and it’s not clear, what name the method should assume for its arguments, when it encounters null . The simplest solution is to provide the parameter names explicitly:

private static String[] parameterNames=< "name", "address" >; public void parametersForValidation(String name,String address) < validateParameters(parameterNames, name, address); >private void validateParameters(String[] name, Object. values) < for(int ix=0; ix> > 

For comparison, if you are using Java 8 and have compiled your code using the -parameters option, the parameter names are available at runtime via Reflection, i.e. you can use

public void parametersForValidation(String name, String address) < String[] names; try < names = Arrays.stream(getClass() .getMethod("parametersForValidation", String.class, String.class) .getParameters()).map(Parameter::getName).toArray(String[]::new); >catch(ReflectiveOperationException ex) < throw new AssertionError(ex); >validateParameters(names, name, address); > private void validateParameters(String[] name, Object. values) < for(int ix=0; ix> > 

which is obviously not simpler than just providing the names and exchanges the explicit list of names with an explicit list of the name and parameter types of the method to look up reflectively.

Читайте также:  Styling td width with css

Источник

How to convert object to query string with spring (or anything else)?

Is there a way to convert object to query parameters of GET request? Some kind of serializer that converts NameValuePair object to name=aaa&value=bbb, so that string can be attached to the GET request. In other words, I’m looking for a library that takes
1. url ( http://localhost/bla )
2. Object:
public class Obj String id;
List entities;
>
And converts it to:
http://localhost/bla?id=abc&entities[0].name=aaa&entities[0].value=bbb Spring RestTemplate is not what I’m looking for as it does all other things except converting object to parameters string.

Actually I asked about the opposite. I want to write java client that can sent requests to such a controller. I need to convert an object into parameters.

3 Answers 3

// object to Map ObjectMapper objectMapper = new ObjectMapper(); Map map = objectMapper.convertValue(obj, new TypeReference>() <>); // Map to MultiValueMap LinkedMultiValueMap linkedMultiValueMap = new LinkedMultiValueMap<>(); map.entrySet().forEach(e -> linkedMultiValueMap.add(e.getKey(), e.getValue())); // call RestTemplate.exchange return getRestTemplate().exchange( uriBuilder().path("your-path").queryParams(linkedMultiValueMap).build().toUri(), HttpMethod.GET, null, new ParameterizedTypeReference>() <>).getBody(); 
Client.create().resource("url").queryParam(key, value).get() 
package util; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; public class ObjectConvertUtil < // convert Object to queryString public static String toQS(Object object)< // Object -->map ObjectMapper objectMapper = new ObjectMapper(); Map map = objectMapper.convertValue( object, Map.class); StringBuilder qs = new StringBuilder(); for (String key : map.keySet()) < if (map.get(key) == null)< continue; >// key=value& qs.append(key); qs.append("="); qs.append(map.get(key)); qs.append("&"); > // delete last '&' if (qs.length() != 0) < qs.deleteCharAt(qs.length() - 1); >return qs.toString(); > > 
  com.fasterxml.jackson.core jackson-databind 2.9.8  

Источник

How to get the string value of a parameter in Java?

I’m trying to save a parameter as a property, the parameter is : testSpeed ( = «20» ) , and I have a method :

saveProperty(String Parameter) 
testSpeed : 20 testHeight : 300 

My question is : In Java is it possible to get the name of the parameter, in this case the parameter passed to saveProperty() is testSpeed , and it’s name is «testSpeed» , how to get this string from inside of saveProperty() , so I don’t have to do the following to save it :

saveProperty(String Name,String Value); 
saveProperty("testSpeed",testSpeed) 

I know how to use a property file, I’m just using it as an example, maybe it caused some confusion when I mentioned property file. The essence of the question is : how to get the name of a parameter passed into a method.

void someMethod(String Parameter_XYZ) < // In here if I call someMethod(testSpeed), how to get the string "testSpeed", // not it's value, but it's name, // exactly spelled as "testSpeed" ? >

3 Answers 3

First of all correct format of property file is this:

testSpeed=20 testHeight=300 

Now to pull any property from this you need to pass key name, which you’re already doing in saveProperty(String name, String value) method. However if I understood your question correctly then you want to avoid passing property name. You can have some custom methods like this:

void saveTestSpeed(String value) < saveProperty("testSpeed", value); >Strig getTestSpeed()

EDIT: Based on your edited question.

Читайте также:  Jquery css function undefined

No it is not possible in Java.

Please remember that Java is strictly pass-by-value that makes it impossible to figure out the name of actual variable name at callee’s end. Inside the saveProperty method we can only get the value of the arguments since in Java Object references are passed by value not by name.

This is not practical also since there is nothing that stops method being called like:

In the case what should be the name of the property?

Источник

Java get variable name as string

Is it possible to implement this super_func , as shown above? Or maybe I am asking for too much? EDIT: I am not allowed to use enum. I can: a) use a map (as someone pointed, or 2 array lists) or
b) do this with some pro way (but it doesn’t seem possible).

Is this just an idle question? Why do you need to do this? Maybe you should explain what you’re trying to do that lead you to need this.

5 Answers 5

I don’t know what this value is supposed to represent, but you could use an Enum.

enum Animal < DRAGON(5), SNAKE(6); private final int a; private Animal(int a)< this.a = a; >public int getA() < return a; >> 
String this_item = "DRAGON"; int item_value = Animal.valueOf(this_item).getA();//5 

You can get the value of a variable with Java Reflection tricks, but why not declaring a simple enum and using it:

While it’s technically possible to do this using reflection, I’d strongly recommend you to rethink your structure, and consider one of the alternatives that have been mentioned in the other answers.

The simplest would probably be to use a map

import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; public class VariableNameTest < private static final Mapmap; static < Mapm = new LinkedHashMap(); m.put("DRAGON",5); m.put("SNAKE",6); map = Collections.unmodifiableMap(m); > public static void main(String[] args) < System.out.println(getValue("DRAGON")); System.out.println(getValue("SNAKE")); System.out.println(getValue("Boo!")); >public static int getValue(String name) < Integer i = map.get(name); if (i == null) < // Do some error handling here! >return i; > > 

But if your intention is to extend this with additional functionality, you should probably introduce a class like it was recommended in https://stackoverflow.com/a/23846279/3182664

Just for completeness: The reflection solution, not recommended!

import java.lang.reflect.Field; public class VariableNameTest < static final int DRAGON = 5; static final int SNAKE = 6; public static void main(String[] args) < System.out.println(getValue("DRAGON")); System.out.println(getValue("SNAKE")); System.out.println(getValue("Boo!")); >private static int getValue(String name) < try < Classc = VariableNameTest.class; Field f = c.getDeclaredField(name); return f.getInt(null); > catch (NoSuchFieldException e) < // Many things e.printStackTrace(); >catch (SecurityException e) < // may cause e.printStackTrace(); >catch (IllegalArgumentException e) < // this to e.printStackTrace(); >catch (IllegalAccessException e) < // fail horribly e.printStackTrace(); >return 0; > > 

Источник

Читайте также:  Java все классы должны определять конструктор

Parameterized Strings in Java

I find myself very frequently wanting to write reusable strings with parameter placeholders in them, almost exactly like what you’d find in an SQL PreparedStatement . Here’s an example:

private static final String warning = "You requested ? but were assigned ? instead."; public void addWarning(Element E, String requested, String actual) < warning.addParam(0, requested); warning.addParam(1, actual); e.setText(warning); //warning.reset() or something, I haven't sorted that out yet. >

Does something like this exist already in Java? Or, is there a better way to address something like this? What I’m really asking: is this ideal?

9 Answers 9

String.format()

Since Java 5, you can use String.format to parametrize Strings. Example:

String fs; fs = String.format("The value of the float " + "variable is %f, while " + "the value of the " + "integer variable is %d, " + " and the string is %s", floatVar, intVar, stringVar); 

Alternatively, you could just create a wrapper for the String to do something more fancy.

MessageFormat

Per the comment by Max and answer by Affe, you can localize your parameterized String with the MessageFormat class.

And use the MessageFormat class if you would like to format strings in a locale and language independent way.

You could use String.format . Something like:

String message = String.format("You requested %2$s but were assigned %1$s", "foo", "bar"); 
"You requested bar but were assigned foo" 

It is built-in, yes. The class you’re looking for is java.text.MessageFormat

The String class provides the following format method, http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html. For example (as per the original post):

private final static String string = "You requested %s but were assigned %s instead."; public void addWarning(Element e, String requested, String actual) < String warning = String.format(string, requested, actual); e.setText(warning); 

Since Java 15, String has a method formatted equivalent to String.format .

So you can directly use "var1 is %s, var2 is %s".formatted(var1, var2);

I would probably do something like:

private final String warning = String.format("You requested %s but were assigned %s instead.", requested, actual); 

If you wanted to put the parameterized string before the call to format the string you could do something like what you see below, although this is less clear.

Neither of these solutions are inherently localizeable; you may want to consider something like a .properties file if you wish to support non-English locales.

private static final String warning = "You requested %s but were assigned %s instead."; public void addWarning(Element E, String requested, String actual) < e.setText(String.format(warning, requested, actual); //warning.reset() or something, I haven't sorted that out yet. >

Источник

Оцените статью