To convert any object to string there are several methods in Java
String convertedToString = String.valueOf(Object); //method 1
String convertedToString = "" + Object; //method 2
String convertedToString = Object.toString(); //method 3
I would prefer the first and third
EDIT
If working in kotlin, the official android language
val number: Int = 12345
String convertAndAppendToString = "number = $number" //method 1
String convertObjectMemberToString = "number = ${Object.number}" //method 2
String convertedToString = Object.toString() //method 3
Answer from Salmaan on Stack OverflowTo convert any object to string there are several methods in Java
String convertedToString = String.valueOf(Object); //method 1
String convertedToString = "" + Object; //method 2
String convertedToString = Object.toString(); //method 3
I would prefer the first and third
EDIT
If working in kotlin, the official android language
val number: Int = 12345
String convertAndAppendToString = "number = $number" //method 1
String convertObjectMemberToString = "number = ${Object.number}" //method 2
String convertedToString = Object.toString() //method 3
If the class does not have toString() method, then you can use ToStringBuilder class from org.apache.commons:commons-lang3
pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.18.0</version>
</dependency>
build.gradle:
implementation 'org.apache.commons:commons-lang3:3.18.0'
code:
ToStringBuilder.reflectionToString(yourObject)
I'm afraid your map contains something other than String objects. If you call toString() on a String object, you obtain the string itself.
What you get [Ljava.lang.String indicates you might have a String array.
Might not be so related to the issue above. However if you are looking for a way to serialize Java object as string, this could come in hand
package pt.iol.security;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;
public class ObjectUtil {
static final Base64 base64 = new Base64();
public static String serializeObjectToString(Object object) throws IOException {
try (
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(arrayOutputStream);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(gzipOutputStream);) {
objectOutputStream.writeObject(object);
objectOutputStream.flush();
return new String(base64.encode(arrayOutputStream.toByteArray()));
}
}
public static Object deserializeObjectFromString(String objectString) throws IOException, ClassNotFoundException {
try (
ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(base64.decode(objectString));
GZIPInputStream gzipInputStream = new GZIPInputStream(arrayInputStream);
ObjectInputStream objectInputStream = new ObjectInputStream(gzipInputStream)) {
return objectInputStream.readObject();
}
}
}
java - How get the value from a Object of class through a String? - Stack Overflow
java - Get instanced object by String - Stack Overflow
How to get string value from a Java field via reflection? - Stack Overflow
network programming - How to turn a String value into a object reference in Java? - Stack Overflow
Sorry its actualy look like this Name:armand,Age:22,etc. But i am very bad in regex, this is hard for me to solve.
Given String s = "Name:armand,Age:22";
Here is a hint:
s.split(",")[0].split(":") will give you armand,
s.split(",")[1].split(":") will give you 22
no regular expression knowledge needed.
Some people, when confronted with a problem, think โI know, I'll use regular expressions.โ Now they have two problems. - Jamie Zawinski
Depends on what you really want to do, for example if you only want to get the value of a given key, given that key and value are separated by colon and key/value are separated by comma, you can just split in this way string first by comma and then by colon :
String[] couple = string.split(",");
for(int i =0; i < couple.length ; i++) {
String[] items =couple[i].split(":");
items[0]; //Key
items[1]; //Value
}
If you want to do it with a regular expression you can do in this way :
String string = "Name:armand,Age:22,";
Pattern pattern = Pattern.compile("(\\w+?):(\\w+?),");
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
String key = matcher.group(1);
String value = matcher.group(2);
System.out.println("Key : " + key + " value : " + value);
}
It seems that you want to "identify" objects by some string based name. If so, the appropriate data structure in Java is a Map. In your case, you would need something like:
Map<String, Integer> registry = new HashMap<>();
registry.put("t1", 15);
registry.put("t2", 20);
And later you can query this using
Integer value = registry.get("t1");
If you want to store "arbitrary" values, you can/have to use a Map<String, ? extends Object> though. But that isn't exactly a good approach in the first place; as you loose all the compile-time checking that generics would give you.
If you are using Java 8, you may modify the getValue method in the following way:
public <T> T getValue(Function<Integer, T> parser) {
return Optional.of(value).map(parser).get();
}
Example:
Register $t2 = new Register("
t2.setValue(20);
//getting values
Long longValue = $t2.getValue(Integer::longValue);
Double doubleValue = $t2.getValue(Integer::doubleValue);
String stringValue = $t2.getValue(i -> i.toString());
Integer integerValue = $t2.getValue(Integer::valueOf);
System.out.print("long: " + longValue + ", double: " + doubleValue + ", string: " + stringValue + ", integer: " + integerValue);
Output:
long: 20, double: 20.0, string: 20, integer: 20
Here's an example
If it's a class field, you can get it by name like this.
import java.lang.reflect.Method;
public class Test {
public String stringInstance = "first;second";
public void Foo() {
try {
Object instance = getClass().getDeclaredField("stringInstance").get(this);
Method m = instance.getClass().getMethod("split", String.class);
Object returnValue = m.invoke(instance, ";");
if(returnValue instanceof String[])
{
for(String s : (String[])returnValue )
{
System.out.println(s);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String a[]){
new Test().Foo();
}
}
If it's a local method variable you are trying to invoke on, then you might be able to get at to the variable in from the current method from the call stack Thread.currentThread().getStackTrace() maybe.
It is hard to make out what you are asking, but you can fetch field values by name using reflection. Something like this:
Class c = this.getClass(); // or Someclass.class
Field f = c.getDeclaredField("xyz");
String value = (String) f.get(this);
... = value.split("_");
(I've left out a lot of exception handling ...)
But as a comment points out, if you are really trying to implement an associative array, there are better ways of doing this in Java; e.g. using a Map class.
It looks like you need a reference to an instance of the class. You would want to call get and pass in the reference, casting the return to a String.
You can use get as follows:
String strValue = (String) field.get (objectReference);
In ideal situations,Class does not hold data. It merely holds the information about the structure and behavior of its instances and Instances of the Classes hold your data to use. So your extractStringFromField method can not extract values unless you pass any instances (from where it will actually extract values).
If the name of the parameter of the reference, you are passing to extract value is instance, then you can easily get what you want like bellow:
String strValue = (String)field.get(instance);
Replace below line
TextView otherUid = findViewById(R.id.uidTextView);
to:
TextView otherUid = view.findViewById(R.id.uidTextView);
It should work
... Hi Sam, You need to set the text of the second TextView before getting it. You can do this adding android:text to the second textview in the xml to have static text (the default value). To have dynamic text into your second textview just set the text when you are creating the element of the List. Hope this help.
Cheers
You should use array of strings for this purpose.
String[] Qty = {"1","2"};
for(int j = 0 ; j < 2 ;j++)
{
System.out.println("qtyString = " + Qty[j]);
}
String array is needed if you want to print a list of string:
String[] Qty = {"1", "2"};
String qtyString = null;
for (int j = 0; i<=1; j++) {
qtyString = Qty[j];
System.out.println("qtyString = " + qtyString);
}
output:
qtyString = 1
qtyString = 2
Hello guys, I would like to know the best way to convert object to string with commas separating the year month & day in format (yyyy,mm,dd) . I am trying to do so for the program to place information into a data file. The conversion follows the code line below. I seek your kind assistance and many thanks.
MyDate MyDate = cannedFood.getexpiryDate(); // to convert object MyDate into string