Valor variável static com reflection?

5 respostas
viniciusalvess

Salve galera, talvez minha pergunta seja simples , mas pesquisei por algum tempo e ainda não encontrei ma resposta.

Com reflection consigo pegar o valor dos campos de um “objeto” instancia sem problema.
Gostaria de saber se essa classe tem um campo static final ou seja uma contante , se é possível pegar o valor dela sem instancia ?

5 Respostas

viniciusalvess

Desculpe esqueci de agregar acima ,até agora resolvi dessa forma. Tem alguma forma melhor de resolver ?

public static void main(String[] args) {
		Class<Cliente> c = Cliente.class;
		try {
			Field f = c.getDeclaredField("columns");
			Class v = f.getType();
			System.out.println(v);
			System.out.println(f.get(c.newInstance()));
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
ViniGodoy

Se o campo for estático, você pode chamar f.get(null);

O newInstance() irá forçar uma chamada ao construtor, o que é inútil e até indesejável no caso de um campo estático.

viniciusalvess

ViniGodoy:
Se o campo for estático, você pode chamar f.get(null);

O newInstance() irá forçar uma chamada ao construtor, o que é inútil e até indesejável no caso de um campo estático.

fiz assim:

public static String getVariableValue(Class&lt;?&gt; c,String fieldName){

//		Object v = c.getClass();
		String result  = null;
		try {
			Field f = c.getDeclaredField(fieldName);
//			Class v = f.getType();
//			System.out.println(v);
//			if(f.isAccessible()){
				result = (String) f.get(null);
//			}else {
//				return "";
//			}
			
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result ;

	}
	
	public static void main(String[] args) {
		System.out.println(ReflectionUtils.getVariableValue(Cliente.class, "columns"));
	}
se eu tirar o teste isAccecible();

me retorna um IllegalArgumentException dizendo:

Class br.com.jstore.util.ReflectionUtils can not access a member of class br.com.jstore.gerencia.model.Cliente with modifiers "private static final";
ViniGodoy

É porque o campo é privado. Então você tem que chamar
f.setAcessible(true);

Antes de tentar dar o get nele.

viniciusalvess

ViniGodoy:
É porque o campo é privado. Então você tem que chamar
f.setAcessible(true);

Antes de tentar dar o get nele.

Obrigado Vini por compartilhar seu conhecimento !
deu certo aqui.

Criado 22 de janeiro de 2012
Ultima resposta 22 de jan. de 2012
Respostas 5
Participantes 2