/**
* Returns the name of the class, as the JVM would output it. For instance, for an int, "I" is returned, for an
* array of Objects, "[Ljava/lang/Object;" is returned. If the input is null, null is returned.
*
* @param clazz
* @return
*/
public static String getJVMName(Class clazz) {
if(clazz == null) {
return null;
}
//For arrays, .getName() is fine.
if(clazz.isArray()) {
return clazz.getName().replace('.', '/');
}
if(clazz == boolean.class) {
return "Z";
} else if(clazz == byte.class) {
return "B";
} else if(clazz == short.class) {
return "S";
} else if(clazz == int.class) {
return "I";
} else if(clazz == long.class) {
return "J";
} else if(clazz == float.class) {
return "F";
} else if(clazz == double.class) {
return "D";
} else if(clazz == char.class) {
return "C";
} else {
return "L" + clazz.getName().replace('.', '/') + ";";
}
}
/**
* Generically and dynamically returns the array class type for the given class type. The dynamic equivalent of
* sending {@code String.class} and getting {@code String[].class}. Works with array types as well.
* @param clazz The class to convert to an array type.
* @return The array type of the input class.
*/
public static Class<?> getArrayClassFromType(Class<?> clazz) {
Objects.requireNonNull(clazz);
try {
return Class.forName("[" + getJVMName(clazz).replace('/', '.'));
} catch(ClassNotFoundException ex) {
// This cannot naturally happen, as we are simply creating an array type for a real type that has
// clearly already been loaded.
throw new NoClassDefFoundError(ex.getMessage());
}
}
5条答案
按热度按时间qvtsj1bj1#
所以,我就是其中之一,喜欢摆弄琴弦。所以,这里有一个更通用的解决方案,它采用这种方法,并且仍然适用于任意类类型。当然,这比你的答案要复杂得多,但不管怎样,让它成为通用的答案要比公认的答案更复杂得多,所以这里有一套完整的代码来让它工作:
请注意,这是我编写的现有库中的代码,这就是我使用getjvmname方法的原因。它可能会被修改为保留点而不是/,但是考虑到它是如何工作的,我在这两种方法之间来回转换。无论如何,这适用于任何类,包括嵌套数组类型。
shstlldc2#
41zrol4v3#
你可以用类名得到它。只要确保你得到的类使用它的类加载器
xzabzqsa4#
从Java12开始,就有
arrayType()
方法。因此:s3fp2yjn5#
如果不想创建示例,可以手动创建数组的规范名称并按名称获取类:
但是jakob jenkov在他的博客中说你的解决方案更好,因为它不需要摆弄弦。