Home > Mobile >  Java: how to convert a class datatype array to a String array?
Java: how to convert a class datatype array to a String array?

Time:11-10

New to programming, I'm trying to convert an array of a class datatype to an array of the datatype String.

I.E:

Class[] array;

String[] stringArray;

Is this possible? Should I use a parse method?

CodePudding user response:

Yes, although it entirely depends on what you are expecting the resulting strings to look like. Do you want the class name? The fully qualified name? Something else? You can do something similar to this, depending on what you need:

Class[] array = ...;
String[] stringArray = Arrays.stream(array).map(Class::getName).toArray(String[]::new);

CodePudding user response:

I'm trying to convert an array of a class datatype to an array of the datatype String

Well, the only way to do it, which makes sense is like this

Class[] classes = {Runnable.class, RuntimeException.class};
String[] strings = new String[classes.length];

var curPos=0;
for(var c : classes) {
    strings[curPos]=classes[curPos].toString();
    curPos  ;
}

for(var str : strings) {
    System.out.println(str);
}

Does this solve your problem? Tell me in the comments. Also, why exactly do you want a transformation like this?

  • Related