Passando null para method.invoke()

4 respostas
P

Olá.

Preciso buscar por reflexão um método, e então utilizar este método. O meu método recebe uma instancia de outra classe que possuo, porém preciso passar null para ele.
O trecho de código que estou tentando utilizar é similar a este:

teste t = new teste();
		Method[] methods = t.getClass().getMethods();
		for (Method method : methods) {
			try {
				method.invoke(t, null);
			} catch (Exception e) {
				System.out.println("deu erro");
			}
		}

Porém ao executar dá erro. Se eu passar uma instancia da classe que o método está esperando como argumento, funciona… alguem sabe dizer como posso passar null?

4 Respostas

davidbuzatto

Lendo a documentação…

public Object invoke(Object obj, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.

If the underlying method is static, then the specified obj argument is ignored. It may be null.

If the number of formal parameters required by the underlying method is 0, the supplied args array may be of length 0 or null.

If the underlying method is an instance method, it is invoked using dynamic method lookup as documented in The Java Language Specification, Second Edition, section 15.12.4.4; in particular, overriding based on the runtime type of the target object will occur.

If the underlying method is static, the class that declared the method is initialized if it has not already been initialized.

If the method completes normally, the value it returns is returned to the caller of invoke; if the value has a primitive type, it is first appropriately wrapped in an object. However, if the value has the type of an array of a primitive type, the elements of the array are not wrapped in objects; in other words, an array of primitive type is returned. If the underlying method return type is void, the invocation returns null.

Parameters:
obj - the object the underlying method is invoked from
args - the arguments used for the method call

Returns:
the result of dispatching the method represented by this object on obj with parameters args

Seu código cai no segundo item, ou seja, passar null indica que não está sendo passado nenhum parâmetro.
Provavelmente você precisará refatorar o seu método.
Outra coisa, você está invocando TODOS os métodos públicos da classe “teste”. Você não deveria escolher apenas um método?

E

Use new Object []{null} em vez de só passar “null”.

davidbuzatto

Boa. Não tinha pensado nisso.

P

Perfeito! Usando new Object[] {null} dá certo.

Valeu!

Criado 25 de janeiro de 2012
Ultima resposta 27 de jan. de 2012
Respostas 4
Participantes 3