Java 反射:类数组与参数类型数组 [英] Java reflection: array of classes vs. array of parameter types

查看:46
本文介绍了Java 反射:类数组与参数类型数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Method 类的对象 m.我调用了 m.getParameterTypes() 来创建方法参数的数组 params.

I have an object m of class Method. I invoked m.getParameterTypes() to create an array params of the method's parameters.

我还有一个对象数组 arr.我想检查 arr 中的对象是否与 params 中的类型具有相同的类型(并且顺序相同).

I also have an array arr of Objects. I wanted to check if the objects in arr are of the same types as the types in params (and in the same order).

我所做的是创建一个数组类,其中包含 arr 中每个对象的类.然后我尝试将类与参数进行比较.结果它们永远不可能相等,因为 classes 数组中的类采用 java.lang.String 格式,而 param 数组中的参数采用 String.如何比较数组?如何更改其中之一的格式?

What I did was to create an array classes which includes the class of each object in arr. Then I tried to compare classes with params. Turns out they can never be equal because the classes in the classes array are in the format of java.lang.String and the parameters in the param array are in the format of String. How can I compare the arrays? How can I change the format of one of them?

推荐答案

getParameterTypes() 返回一个 Class[] 而实际的参数本身将是对象(因此您将拥有一个 Object[]).要检查参数是否有效,您可以使用:

getParameterTypes() returns a Class<?>[] whereas the actual arguments themselves will be objects (so you'll have an Object[]). To check that the arguments are valid, you could use:

if (parameterTypes.length != arr.length) {
  // Invalid: wrong number of arguments
}

for (int i=0; i < parameterTypes.length; i++) {
  if (arr[i] == null && parameterTypes[i].isPrimitive()) {
    // Invalid: can't pass null for a primitive parameter
  } else if (arr[i] != null && !parameterTypes[i].isInstance(arr[i])) {
     // Invalid: invalid argument type
  } else {
     // Valid
  }
}

(当然,对有效/无效的情况做任何你需要做的事情.)

(Do whatever you need to do for the valid/invalid cases, of course.)

这篇关于Java 反射:类数组与参数类型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆