Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use getMethod() with primitive types?

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); 
like image 978
yegor256 Avatar asked Feb 17 '11 18:02

yegor256


People also ask

How can we use primitive data types as objects?

An object of Double is created. An object of Boolean is created. In the above example, we have created variables of primitive types ( int , double , and boolean ). Here, we have used the valueOf() method of the Wrapper class ( Integer , Double , and Boolean ) to convert the primitive types to the objects.

Can collections hold primitive types?

Collections are the framework used to store and manipulate a group of objects. Java Collection means a single unit of objects. Since the above two statements are true, generic Java collections can not store primitive types directly.

Do primitive types have methods?

In JavaScript, a primitive (primitive value, primitive data type) is data that is not an object and has no methods or properties. There are 7 primitive data types: string. number.

What is primitive type parameters?

Primitive parameters are parameters of a function that are of primitive types. This means in a function with parameters, any parameter that has type number, string, or boolean is a primitive parameter. When you call a function with parameters, you supply it with arguments.


2 Answers

There's just an int.class.

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

An alternative is Integer.TYPE.

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

The same applies on other primitives.

like image 164
BalusC Avatar answered Oct 07 '22 06:10

BalusC


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.

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

like image 23
paulturnip Avatar answered Oct 07 '22 05:10

paulturnip