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 ?
Desculpe esqueci de agregar acima ,até agora resolvi dessa forma. Tem alguma forma melhor de resolver ?
publicstaticvoidmain(String[]args){Class<Cliente>c=Cliente.class;try{Fieldf=c.getDeclaredField("columns");Classv=f.getType();System.out.println(v);System.out.println(f.get(c.newInstance()));}catch(NoSuchFieldExceptione){// TODO Auto-generated catch blocke.printStackTrace();}catch(SecurityExceptione){// TODO Auto-generated catch blocke.printStackTrace();}catch(IllegalArgumentExceptione){// TODO Auto-generated catch blocke.printStackTrace();}catch(IllegalAccessExceptione){// TODO Auto-generated catch blocke.printStackTrace();}catch(InstantiationExceptione){// TODO Auto-generated catch blocke.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:
publicstaticStringgetVariableValue(Class<?>c,StringfieldName){// Object v = c.getClass();Stringresult=null;try{Fieldf=c.getDeclaredField(fieldName);// Class v = f.getType();// System.out.println(v);// if(f.isAccessible()){result=(String)f.get(null);// }else {// return "";// }}catch(NoSuchFieldExceptione){// TODO Auto-generated catch blocke.printStackTrace();}catch(SecurityExceptione){// TODO Auto-generated catch blocke.printStackTrace();}catch(IllegalArgumentExceptione){// TODO Auto-generated catch blocke.printStackTrace();}catch(IllegalAccessExceptione){// TODO Auto-generated catch blocke.printStackTrace();}returnresult;}publicstaticvoidmain(String[]args){System.out.println(ReflectionUtils.getVariableValue(Cliente.class,"columns"));}