0

This is not a duplicate, please read the question and understand that I have an Object (not a char[], not an Object[], but an Object)

public String getStringFromObject(Object o){
  // What do I do here to get a String?  o is actually a char[]
}

I have a java Object that represents a character array:

I get passed an Object cred into a method

L.info("Credentials component type is {} and is array -> {}", 
       cred.getClass().getComponentType(), cred.getClass().isArray());

This prints: Token's credentials are: [s, d, f] and type is [C

How do I get this into a String? I can't figure out how to cast the Object to any kind of [] array. If it was Object[] to start with it would not be a problem.

mikeb
  • 10,578
  • 7
  • 62
  • 120
  • `[C` means it's a `char[]` so cast to that. Then call the `String(char[])` constructor. – Thomas Jun 13 '16 at 16:26
  • The output seems from a different log statement. Are you sure you posted the right one? – M A Jun 13 '16 at 16:27
  • 1
    Possible duplicate of [How to convert a char array back to a string?](http://stackoverflow.com/questions/7655127/how-to-convert-a-char-array-back-to-a-string) –  Jun 13 '16 at 16:27
  • Why are you passing in an Object if it is a char[]? Why not just pass the character array? (I'm mainly asking this for my own selfish education). Is this for study? – David Jun 13 '16 at 16:44
  • Why you are doing it , when you can directly convert Character array to `String`? Help us – Ravi Rajput Jun 13 '16 at 17:42

1 Answers1

4

If you have a char[] and you want to convert it to a String simply use the constructor

public String(char[] value)

From javadoc:

Allocates a new String so that it represents the sequence of characters currently contained in the character array argument. The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.


Note

If you have an Object that is a char[] here is what you have:

char[] x = ....;
Object objectIsACharArray = x;
String s = new String((char[]) x);

If the Object is not a char[] but is something that represent or hold a char array you need a custom code to convert it to a String.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • You didn't understand the question. I have an Object. – mikeb Jun 13 '16 at 16:35
  • There is no `String` constructor that takes an `Object`. You can't just declare `x` as `Object` then call `new String(x)`, for this reason. Casting is an option here though, I believe. – bcsb1001 Jun 13 '16 at 16:46