我正在尝试获取传递的Object的类名。但是Object#getClass()只返回java.lang.Class。以下是obj是net.minecraft.server.v1_8_R1.IChatBaseComponent
的实例的示例:
System.out.println("logging x2: " + obj.getClass()); // class java.lang.Class
为什么会发生这种情况,我该如何解决这个问题。不,我无法使用newInstance
或instanceof
或isAssignableFrom
,因为整个方法用于确定传递对象的类名。
完整的方法如下所示:
public Method getMethod(String name, Class<?>... paramTypes) throws Exception {
Class<?>[] types = toPrimitiveTypeArray(paramTypes, false);
for (Method method : this.getClazz().getMethods()) {
Class<?>[] methodTypes = toPrimitiveTypeArray(method.getParameterTypes(), true); // here is where it logs
if (method.getName().equals(name) && isEqualsTypeArray(methodTypes, types)) {
method.setAccessible(true);
return method;
}
}
System.out.println(StringUtil.format("The method {0} was not found with parameters {1}!", name, Arrays.asList(types)));
return null;
}
private static Class<?>[] toPrimitiveTypeArray(Object[] objects, boolean log) {
Class<?>[] types = new Class<?>[objects != null ? objects.length : 0];
for (int i = 0; i < types.length; i++) {
if (log) System.out.println("logging x1: " + objects[i]); // interface net.minecraft.server.v1_8_R1.IChatBaseComponent
if (log) System.out.println("logging x2: " + objects[i].getClass()); // class java.lang.Class
if (log) System.out.println("logging x3: " + objects[i].getClass().getName()); // java.lang.Class
types[i] = getPrimitiveType(objects[i].getClass()); // This just swaps out primitives for their class-versions, or returns the passed class, the problem happens before this
}
return types;
}
答案 0 :(得分:2)
看起来这就是你想要的。
private static Class<?>[] toPrimitiveTypeArray(
// vvvvvvvv
Class<?>[] objects, boolean log) {
...
for (int i = 0; i < types.length; i++) {
...
// vvvvvvvvvv
types[i] = getPrimitiveType(objects[i]);
}
...
}
getParameterTypes
已经返回Class
数组,您隐式向上转发Object
。
或者你可能想要做getPrimitiveType(objects[i].getName())
你现在可以做的事情。 (但你的描述对我来说并不清楚,所以我不能肯定地说。)
答案 1 :(得分:0)
我试图获取传递的对象的类名
private static void toPrimitiveTypeArray(Object[] objects, boolean log) {
for (int i = 0; i < objects.length; i++) {
System.out.println(objects[i].getClass().getSimpleName());
}
如果您只想返回Object数组中所有类的类名。
答案 2 :(得分:-2)
objects[i].getClass().getName()
应该有用。