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.

5
  • [C means it's a char[] so cast to that. Then call the String(char[]) constructor. Commented Jun 13, 2016 at 16:26
  • The output seems from a different log statement. Are you sure you posted the right one? Commented Jun 13, 2016 at 16:27
  • 1
    Possible duplicate of How to convert a char array back to a string? Commented Jun 13, 2016 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? Commented Jun 13, 2016 at 16:44
  • Why you are doing it , when you can directly convert Character array to String? Help us Commented Jun 13, 2016 at 17:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You didn't understand the question. I have an Object.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.