如何对原始类型使用getMethod() ?

时间:2022-04-17 12:57:21

This is the class:

这是类:

class Foo {
  public void bar(int a, Object b) {
  }
}

Now I'm trying to get "reflect" this method from the class:

现在我想从课堂上得到"反射"这个方法

Class c = Foo.class;
Class[] types = { ... }; // what should be here?
Method m = c.getMethod("bar", types);

2 个解决方案

#1


80  

There's just an int.class.

只有一个int.class。

Class[] types = { int.class, Object.class };

An alternative is Integer.TYPE.

另一种是Integer.TYPE。

Class[] types = { Integer.TYPE, Object.class };

The same applies on other primitives.

其他原语也是如此。

#2


1  

The parameter of the method is a primitive short not an Object Short.

该方法的参数是一个原始的短而不是对象。

Reflection will not find the method because you specified an object short. The parameters in getMethod() have to match exactly.

反射不会找到方法,因为您指定了一个对象为short。getMethod()中的参数必须完全匹配。

EDIT: The question was changed. Initially, the question was to find a method that takes a single primitive short.

编辑:问题变了。最初,问题是找到一个方法,该方法只使用一个简单的原语。

#1


80  

There's just an int.class.

只有一个int.class。

Class[] types = { int.class, Object.class };

An alternative is Integer.TYPE.

另一种是Integer.TYPE。

Class[] types = { Integer.TYPE, Object.class };

The same applies on other primitives.

其他原语也是如此。

#2


1  

The parameter of the method is a primitive short not an Object Short.

该方法的参数是一个原始的短而不是对象。

Reflection will not find the method because you specified an object short. The parameters in getMethod() have to match exactly.

反射不会找到方法,因为您指定了一个对象为short。getMethod()中的参数必须完全匹配。

EDIT: The question was changed. Initially, the question was to find a method that takes a single primitive short.

编辑:问题变了。最初,问题是找到一个方法,该方法只使用一个简单的原语。