Reflection

5 respostas
Ruben_Lins

Oi, pessoal

Como faço para acessar o valor de um atributo privado usando Reflection ?

Ou seja, como faço para invocar o método getXXX de um atributo privado usando Reflection ?

Abraço,

Ruben Lins

5 Respostas

rodrigoallemand
public class Teste {
	
	private String valor = "valor";
	
	public static void main(String[] args) {
		try {
			Teste teste = new Teste();
			Field field = teste.getClass().getDeclaredField("valor");
			field.setAccessible(true);
			System.out.println(field.get(teste));
		} catch (Exception e){
			System.out.println("Deu merda: " + e.getMessage());
		}
	}

}
xandroalmeida

Commons beanutils http://commons.apache.org/beanutils/

http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/package-summary.html#standard.basic

PropertyUtils.getSimpleProperty(bean, "XXX");
T

Ele quer chamar o getter; ele não quer o valor do campo. Neste caso é mais fácil (não é preciso usar “setAccessible”), mas por favor confira porque estou escrevendo sem conferir:

public class Teste {
	
	private String valor;
        public String getValor () { return valor; }
	
	public static void main(String[] args) {
		try {
			Teste teste = new Teste();
                        Method method = teste.getClass().getMethod ("getValor");
                        String valor = (String) method.invoke (teste, new Object[] {});
		}catch (Exception e){
			System.out.println("Deu merda: " + e.getMessage());
		}
	}

}
rodrigoallemand
Código do thingol...
public class Teste {
	
	private String valor = "valor";
	
	public String getValor(){
		System.out.println("invocou!");
		return this.valor;
	}
	
	public static void main(String[] args) {
		try {
			Teste teste = new Teste();
			Method method = teste.getClass().getDeclaredMethod("getValor", null); 
			System.out.println(method.invoke(teste, null));
		} catch (Exception e){
			System.out.println("Deu merda: " + e.getMessage());
		}
	}

}
Ruben_Lins

Muito obrigado, pessoal.

Resolvi o meu problema. Optei pela solução dado pelo Rodrigo.
Mas obrigado a todos.

Abraços,

Ruben Lins

Criado 29 de novembro de 2007
Ultima resposta 29 de nov. de 2007
Respostas 5
Participantes 4