Convert object type to string in java

Convert Class Object to Human Readable String

Is there any way in which I can automatically convert a Custom Class Object into a human readable string? e.g. consider the following class:

class Person < String Name; int Salary; . >Person p = new Person(); p.setName("Tony"); p.setSalary(1000); 
Person: Name="Tony", Salary=1000 

yeah, that’s what I’m looking for. But since using reflection gonna make it quite general, I was wondering if there is one already available somewhere!

7 Answers 7

Check method reflectionToString(java.lang.Object) , this will create automatically the representation you are expecting.

Person p = new Person(); p.setName("Tony"); p.setSalary(1000); System.out.println(ToStringBuilder.reflectionToString(p)); 
Person@64578ceb[Name=Tony,Salary=1000] 

sure you can override the toString method of class.

class Person < String name; int salary; . @Override public String toString() < return "Person: Name='" + name + "', Salary https://blogs.oracle.com/CoreJavaTechTips/entry/writing_tostring_methods_tech_days" rel="nofollow">https://blogs.oracle.com/CoreJavaTechTips/entry/writing_tostring_methods_tech_days

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Jul 2, 2012 at 10:30
answered Jul 2, 2012 at 10:21
3
    1
    you mean p.toString(); . or just simply print p java will automatically invoke toString on it to print it.
    – Harry Joy
    Jul 2, 2012 at 10:25
    ya that will print the object as a string.
    – Hemant Metalia
    Jul 2, 2012 at 10:26
    you can also call it by directly object just simply p will also fine if you want to specify explicitly then also you can..
    – Hemant Metalia
    Jul 2, 2012 at 10:29
Add a comment|
3

This is basically what toString is for. But given you want this done automatically, you can create some general service that can do it. Use reflection to iterate all fields, and then print each one's name and value. Simplest way to print their values would be by using their toString, but you can also pass them into that printing service recursively on some cases (you'll have to find the halt condition, of course).

For example, on some class PrintUtils have:

public static void printFields(Object o) < System.out.print(o.getClass.getSimpleName() + ": "); for (Field field : o.getClass().getDeclaredFields()) < field.setAccessible(true); // you also get non-public fields System.out.print(field.getName() + " = " + field.get(o) + ", "); >>

You'll have to handle exceptions etc. and possibly better format the output, of course. Also, this only print fields declared in the current class. If you want fields declared higher in the inheritance hierarchy, you'll have to work a bit more. Lastly, using reflection is much slower than just having a regular toString . If using toString is possible, it is preferable.

Источник

How to convert object array to string array in Java

But this would cause a runtime error: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String; What's the correct way to do it ?

I like waxwing's answer the best : String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class); It's very concise and works. I counted how much time it takes for both his answer and my current approach, they are pretty much the same.

11 Answers 11

Another alternative to System.arraycopy :

String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class); 

Hrm. I couldn't get this one to work, where the long-form example in the original question does work. It throws java.lang.ArrayStoreException. I'm getting the object array from the toArray method on a generic ArrayList containing my custom type. Is this not expected to work with generics or something?

@Ian, the issue is that objectArray contains Objects not Strings (see mmyers comment to my answer which suffers from the same problem).

I just tried this approach and, at least in my case, I found out that performance is not as good as building the array myself by iterating. (Too bad though, I liked it as a one-liner!)

String[] strings = Arrays.stream(objects).toArray(String[]::new); 

To convert an array of other types:

String[] strings = Arrays.stream(obj).map(Object::toString). toArray(String[]::new); 

This is a work of beauty and satisfies the requirement of being able to aesthetically convert a non-String object array to an array of their toString equivalents. The currently accepted answer does not accomplish this.

This works but if your list contains nulls you'll get a NullPointerException. To get around that issue see: stackoverflow.com/questions/4581407/…

I get an Android Studio IDE error when using Arrays.stream . "Cannot resolve method 'stream()'. I know I am on the correct version of Java.

System.arraycopy is probably the most efficient way, but for aesthetics, I'd prefer:

 Arrays.asList(Object_Array).toArray(new String[Object_Array.length]); 

Good point. I understood the toString as just being a way of casting to a String, not the intention of actually replacing the objects with something else. If that is what you need to do, then looping is the only way.

this does not work in Android 2.3.3.. it gives me an error saying that copyof method is not defined. I imported all the right files (ctrl+shift+I).. but it still does not work.

I see that some solutions have been provided but not any causes so I will explain this in detail as I believe it is as important to know what were you doing wrong that just to get "something" that works from the given replies.

First, let's see what Oracle has to say

 * 

The returned array will be "safe" in that no references to it are * maintained by this list. (In other words, this method must * allocate a new array even if this list is backed by an array). * The caller is thus free to modify the returned array.

It may not look important but as you'll see it is. So what does the following line fail? All object in the list are String but it does not convert them, why?

List tList = new ArrayList(); tList.add("4"); tList.add("5"); String tArray[] = (String[]) tList.toArray(); 

Probably, many of you would think that this code is doing the same, but it does not.

Object tSObjectArray[] = new String[2]; String tStringArray[] = (String[]) tSObjectArray; 

When in reality the written code is doing something like this. The javadoc is saying it! It will instatiate a new array, what it will be of Objects.

Object tSObjectArray[] = new Object[2]; String tStringArray[] = (String[]) tSObjectArray; 

So tList.toArray is instantiating a Objects and not Strings.

Therefore, the natural solution that has not been mentioning in this thread, but it is what Oracle recommends is the following

String tArray[] = tList.toArray(new String[0]); 

Источник

how to convert object to string in java

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.

Thanks Vivien, you were the 1st to notify that [Ljava.lang.String indicates a String array, thanks all for helping out 🙂

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(); >> > 

maybe you benefit from converting it to JSON string

String jsonString = new com.google.gson.Gson().toJson(myObject); 

in my case, I wanted to add an object to the response headers but you cant add objects to the headers,

so to solve this I convert my object to JSON string and in the client side I will return that string to JSON again

Looking at the output, it seems that your "temp" is a String array. You need to loop across the array to display each value.

The result is not a String but a String[] . That's why you get this unsuspected printout.

[Ljava.lang.String is a signature of an array of String :
System.out.println(new String[]<>); 

The question how do I convert an object to a String , despite the several answers you see here, and despite the existence of the Object.toString method, is unanswerable, or has infinitely many answers. Because what is being asked for is some kind of text representation or description of the object, and there are infinitely many possible representations. Each representation encodes a particular object instance using a special purpose language (probably a very limited language) or format that is expressive enough to encode all possible object instances.

Before code can be written to convert an object to a String , you must decide on the language/format to be used.

To convert serialize object to String and String to Object

stringToBean(beanToString(new LoginMdp()), LoginMdp.class); public static String beanToString(Object object) throws IOException < ObjectMapper objectMapper = new ObjectMapper(); StringWriter stringEmp = new StringWriter(); objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true); objectMapper.writeValue(stringEmp, object); return stringEmp.toString(); >public static T stringToBean(String content, Class valueType) throws IOException

Источник

Reliably convert any object to String and then back again

Is there a reliable way to convert any object to a String and then back again to the same Object? I've seen some examples of people converting them using toString() and then passing that value into a constructor to reconstruct the object again but not all objects have a constructor like this so that method wont work for all cases. What way will?

7 Answers 7

 String serializedObject = ""; // serialize the object try < ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream so = new ObjectOutputStream(bo); so.writeObject(myObject); so.flush(); serializedObject = bo.toString(); >catch (Exception e) < System.out.println(e); >// deserialize the object try < byte b[] = serializedObject.getBytes(); ByteArrayInputStream bi = new ByteArrayInputStream(b); ObjectInputStream si = new ObjectInputStream(bi); MyObject obj = (MyObject) si.readObject(); >catch (Exception e)

You forgot to mention base64, so that to be able to get a serialized state to a String and back again =)

You need access to the class to do this. What if you're importing the class from somewhere where you don't have access to?

if that class is not final, if it is not referring another non-serializable objects and if you dont have any design problem you can subclass it and then you can serialize this subclass. Well I didnt try:)

If the platform locale is UTF, or some other encoding that is picky about invalid byte sequences for string encoding, this will fail.

try < ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream so = new ObjectOutputStream(bo); so.writeObject(stringList); so.flush(); redisString = new String(Base64.encode(bo.toByteArray())); >catch (Exception e) < e.printStackTrace(); >try < byte b[] = Base64.decode(redisString.getBytes()); ByteArrayInputStream bi = new ByteArrayInputStream(b); ObjectInputStream si = new ObjectInputStream(bi); ListstringList2 = (List)si.readObject(); System.out.println(stringList2.get(1)); > catch (Exception e)

Serialize to byte array, convert to Base64. Then decode Base64 back to byte array and deserialize.

None will work in all cases. An object may, e.g., contain references to other JVMs handling their state, and this state may be not available for you to restore.

Additional problems you're going to meet will include open streams, listening sockets, and almost anything else from the outer world.

There's no need to repeat that most at least two of Java core engineers say that serialization was one of the greatest mistakes a single worst feature in Java, that is, after finalization. (I do love serialization nevertheless, it's handy. But it won't always work.)

Источник

Читайте также:  Java эмулятор для sega
Оцените статью