Ajuda com refection

7 respostas
C

Estou tentando fazer um metodo gravar generico, o q o metodo faiz:

nos paramentros eu mando:
1-uma string com a sql de insercao: “SELECT * FROM fn_inserirCidade(?,?)”
2-o objeto povoado da classe Cidade(como exemplo)

dentro do meu metodo eu pego o tpo da classe, pego os atributos da classe no caso os atributos da classe tem o mesmo nome do campo no banco, Cd_nome, Cd_uf, faco um for e no for eu pegaria o campo, o tipo do campo e executaria o get do campo:

O que eu consigo fazer: pegar o campo, o tipo dele e consigo pegar os metodos;
O que eu não consigo fazer: um if para ver se é do tipo int, boolean, double, só funciona pra String. E não sei como executar o metodo get do respectivo campo.

meu metodo até agora:

public int gravar(String sql,Object obj){
        Connection conexao = null;
        PreparedStatement state = null;
        ResultSet rs = null;
        
        try{
            String str = new String();
            Integer integer = new Integer(0);
            boolean boo = true;
            double doub = 0;
            
            Class cls = obj.getClass();
            Field[] campos = cls.getDeclaredFields();
            
            conexao = this.getConexao();
            
            state = conexao.prepareStatement(sql);
            int numCampos = campos.length;
            for(int i=0;i<numCampos;i++){
                Class classeCampo;
                Field campo = campos[i];
                classeCampo = campo.getType();
                
                if(classeCampo.isInstance(str)){
                    state.setString(i,/*Executa o metodo get do campo*/);
                }else{
                    if(classeCampo.isInstance(new Integer(1))){
                        state.setInt(i,/*Executa o metodo get do campo*/);
                    }else{
                        if(classeCampo.isInstance(boo)){
                            state.setBoolean(i,/*Executa o metodo get do campo*/);
                        }else{
                            if(classeCampo.isInstance(doub)){
                                state.setDouble(i,/*Executa o metodo get do campo*/);
                            }
                        }
                    }
                }
            }
            
        }catch(Throwable e){
            if(e instanceof org.postgresql.util.PSQLException){
                JOptionPane.showMessageDialog(null,e.getMessage());
                retorno = false;
            }else{
                e.printStackTrace();
                retorno = false;
            }
        }finally{
            try{
                if (conexao != null)
                    conexao.close();
                if(state != null)
                    state.close();
            }catch(Throwable e){
                e.printStackTrace();
                retorno = false;
            }
            return retorno;
        }
        return 1;
    }

Nota: só o primeiro if funciona

se alguem puder me ajudar eu agradeco.

>

7 Respostas

C

osmio:
Cara, o primeiro passo é remover esse monte de if´s encadeados.

Procure utilizar o:

if (condicao) {
    // faz algo
} else if (outra_condicao_diferente_da_primeira) {
    // faz outra coisa
} else {
    // senao, faça ainda outra coisa
}

Até!

bele…vou arrumar aki, mais o problema do meu if, é q se o campo dor do tipo int, ele retorna false na minha condicao, ele só consegue acar quando é String, nao sei c é pq int, boolean,… são tipos primitivos…mias nao entra no if

renzonuccitelli

No framework que desenvolvi como trabalho de graduação precisei saber o tipo do argumento (para os tipos primitivos) e setar valores para os mesmos. Segue a classe que faz isso:

public class ExecutionDescriptor  {
	private List <Method> startDocumentMethodsList;
	private List <Method> endDocumentMethodsList;
	private List <ConditionalMethod> startElementMethodsList;
	private List <ConditionalMethod> endElementMethodsList;
	
	
	

	public ExecutionDescriptor() {
		startDocumentMethodsList=new LinkedList<Method>();
		endDocumentMethodsList=new LinkedList<Method>();
		startElementMethodsList=new LinkedList<ConditionalMethod>();
		endElementMethodsList=new LinkedList<ConditionalMethod>();
	}
	
	public void sortConditionalMethods(){
		this.sortElements(startElementMethodsList);
		this.sortElements(endElementMethodsList);
	}
	
	private void sortElements(List<ConditionalMethod> list){
		Collections.sort(list);
	}
	
	public void addStartElementConditionalMethods(List<ConditionalMethod> conditionalMethodsList){
		startElementMethodsList.addAll(conditionalMethodsList);
	}
	
	public void addEndElementConditionalMethods(List<ConditionalMethod> conditionalMethodsList){
		endElementMethodsList.addAll(conditionalMethodsList);
	}
	
	public  void addStartDocumentMethods(List<Method> methodsList){
		startDocumentMethodsList.addAll(methodsList);
	}
	
	public void executeStartDocumentMethods(Object targetObject){
		executeMethodsWithoutParameters(targetObject,startDocumentMethodsList);
	}

	public void addEndDocumentMethods(List<Method> methodsList) {
		if(methodsList.size()>0)
			endDocumentMethodsList.addAll(methodsList);
		
	}
	
	public void executeEndDocumentMethods(Object targetObject){
		executeMethodsWithoutParameters(targetObject,endDocumentMethodsList);
	}
	
	public void executeStartElementMethods(Object targetObject,ContextVariables contextVariables){
		executeConditionalMethods(targetObject,contextVariables,startElementMethodsList);
	}
	
	public void executeEndElementMethods(Object targetObject,ContextVariables contextVariables){
		executeConditionalMethods(targetObject,contextVariables,endElementMethodsList);
	}

	private void executeMethodsWithoutParameters(Object targetObject,List<Method> methodsList) {
		for(Method method:methodsList){
			if(method.getParameterTypes().length==0){
				try {
					method.invoke(targetObject, new Object[]{});
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.getCause().printStackTrace();
				}
			}
				
		}
	}
	
	private void executeConditionalMethods(Object targetObject,ContextVariables contextVariables, List<ConditionalMethod> conditionalMethodsList){
		for(ConditionalMethod cm: conditionalMethodsList){
			if(cm.verify(contextVariables)){
				try {
					Method method=cm.getMethod();
					if(method.getParameterTypes().length==0){
						method.invoke(targetObject, new Object[]{});
					}
					else{
						Object parameters[]=new Object[method.getParameterTypes().length];
						for(int i=0;i<parameters.length;++i){
							parameters[i]=buildParameter(method.getParameterTypes()[i],method.getParameterAnnotations()[i],contextVariables);
						}
						method.invoke(targetObject, parameters);
						
					}
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.getCause().printStackTrace();
					//e.printStackTrace();
//					e.printStackTrace();
				}
			}
		}
	}

	private Object buildParameter(Class<?> parameterClass, Annotation[] parameterAnnotations, ContextVariables contextVariables) {
		if(parameterClass.equals(ContextVariables.class))
			return contextVariables;
		else if(parameterAnnotations.length>0){
			for(Annotation annotation: parameterAnnotations){
				if(annotation instanceof Attribute)
					return buildParameterBasedOnAttribute(parameterClass,(Attribute)annotation,contextVariables);
				else if(annotation instanceof AttributeMap)
					return buildAttributeMap(contextVariables);
				else if(annotation instanceof CurrentBranch)
					return contextVariables.getCurrentBranch();
				else if(annotation instanceof Tag)
					return contextVariables.getLastEvent().getTag();
				else if(annotation instanceof Uri)
					return contextVariables.getLastEvent().getUri();
				else if(annotation instanceof LocalName)
					return contextVariables.getLastEvent().getLocalName();
				else if (annotation instanceof GeneralUseMap)
					return contextVariables.getGeneralUseMap();
				else if(annotation instanceof Body){
					Body body=(Body) annotation;
					if(body.tab()&&body.newLine())
						return contextVariables.getBody();
					else if(body.tab())
						return contextVariables.getBody().replaceAll("\n*", "");
					else if(body.newLine())
						return contextVariables.getBody().replaceAll("\t*", "");
					else 
						return contextVariables.getBody().replaceAll("[\n\t]*", "");
				}
			}
		}
		
		return null;
	}

	private Map<String,String> buildAttributeMap(ContextVariables contextVariables) {
		if(contextVariables.getLastEvent()!=null&&contextVariables.getLastEvent().getAtributesHolder()!=null)
			return contextVariables.getLastEvent().getAtributesHolder().getAttributeMap();
		return null;
	}

	private Object buildParameterBasedOnAttribute(Class parameterClass,
			Attribute attribute, ContextVariables contextVariables) {
		
		String	value=contextVariables.getLastEvent().getAtributesHolder().getValue(attribute.value());
		
		if(parameterClass.equals(Integer.TYPE))
			return buildInt(value);
		else if(parameterClass.equals(Integer.class))
			return buildInteger(value);
		else if(parameterClass.equals(Boolean.TYPE))
			return buildPrimitiveBoolean(value);
		else if(parameterClass.equals(Boolean.class))
			return buildBoolean(value);
		else if(parameterClass.equals(Long.TYPE))
			return buildPrimitiveLong(value);
		else if(parameterClass.equals(Long.class))
			return buildLong(value);
		else if(parameterClass.equals(Float.TYPE))
			return buildPrimitiveFloat(value);
		else if(parameterClass.equals(Float.class))
			return buildFloat(value);
		else if(parameterClass.equals(Double.TYPE))
			return buildPrimitiveDouble(value);
		else if(parameterClass.equals(Double.class))
			return buildDouble(value);
		else if(parameterClass.equals(Short.TYPE))
			return buildPrimitiveShort(value);
		else if(parameterClass.equals(Short.class))
			return buildShort(value);
		else if(parameterClass.equals(Byte.TYPE))
			return buildPrimitiveByte(value);
		else if(parameterClass.equals(Byte.class))
			return buildByte(value);
		else if(parameterClass.equals(Character.TYPE))
			return buildChar(value);
		else if(parameterClass.equals(Character.class))
			return buildCharacter(value);
		else if(parameterClass.equals(String.class))
			return value;
		
		return null;
	}

	private Character buildCharacter(String value) {
		if(value!=null&&value.length()==1){
			return value.charAt(0);
		}
		else
			return null;
	}

	private char buildChar(String value) {
		if(value!=null&&value.length()==1){
			return value.charAt(0);
		}
		else
			return Character.MIN_VALUE;
	}

	private Byte buildByte(String value) {
		if(value!=null){
			return Byte.decode(value);
		}
		else
			return null;
	}

	private byte buildPrimitiveByte(String value) {
		if(value!=null){
			return Byte.parseByte(value);
		}
		else
			return Byte.MIN_VALUE;
	}

	private Short buildShort(String value) {
		if(value!=null){
			return Short.valueOf(value);
		}
		else
			return null;
	}

	private short buildPrimitiveShort(String value) {
		if(value!=null){
			return Short.parseShort(value);
		}
		else
			return Short.MIN_VALUE;
	}

	private Double buildDouble(String value) {
		if(value!=null){
			return Double.valueOf(value);
		}
		else
			return null;
	}

	private double buildPrimitiveDouble(String value) {
		if(value!=null){
			return Double.parseDouble(value);
		}
		else
			return Double.MIN_VALUE;
	}

	private Float buildFloat(String value) {
		if(value!=null){
			return Float.valueOf(value);
		}
		else
			return null;
	}

	private float buildPrimitiveFloat(String value) {
		if(value!=null){
			return Float.parseFloat(value);
		}
		else
			return Float.MIN_VALUE;
	}

	private Long buildLong(String value) {
		if(value!=null){
			return Long.valueOf(value);
		}
		else
			return null;
	}

	private long buildPrimitiveLong(String value) {
		if(value!=null){
			return Long.parseLong(value);
		}
		else
			return Long.MIN_VALUE;
	}

	private boolean buildPrimitiveBoolean(String value) {
		if(value!=null){
			return Boolean.parseBoolean(value);
		}
		else
			return false;
	}
	
	private Boolean buildBoolean(String value) {
		if(value!=null){
			return Boolean.valueOf(value);
		}
		else
			return null;
	}

	private Integer buildInteger(String value) {
		
		if(value!=null){
			return Integer.decode(value);
		}
		else
			return null;
	}

	private int buildInt(String value) {
		
		if(value!=null)
			return Integer.parseInt(value);
		else
			return Integer.MIN_VALUE;
	}
	
}

Repare a partir do método buildParameterBasedOnAttribute que faz exatamente o que vc quer, aliado aos demais métodos privados buld.
Aproveitando para fazer uma proganda :D , o site do framework é: [url]http://jcoltrane.sourceforge.net/index_pt.html[/url]
Espero ter ajudado.

renzonuccitelli

Explicando melhor, vc deve fazer a comparação da classe do objeto com a Classe Wrapper do tipo primitivo seguido da enum TYPE. EX para boolean:

parameterClass.equals(Boolean.TYPE)

onde parameterClass é classe do parametro. Ela retorn true se o parametro for do tipo primitivo boolean e false caso contrário.

A

Ñão sou muito de indicar frameworks a não ser que realmente queira… Se seu objetivo for aprender reflection pode continuar que é um treino massa, se não, já pensou em considerar o hibernate para fazer este trabalho para vc?

Alberto

C

alots_ssa:
Ñão sou muito de indicar frameworks a não ser que realmente queira… Se seu objetivo for aprender reflection pode continuar que é um treino massa, se não, já pensou em considerar o hibernate para fazer este trabalho para vc?

Alberto

Estpu tentando aprender reflection, até de uma lda em hibernate, masi vou deixar pra depois…to meio sem tempo…hehe, mais intaum…estava fazendo o meu metodo e funciona perfeitamente…pra classes que nao herdam de nenhuma outra, masi quando eu tenho uma heranca, eu nao cnsigo pegar os nomes ds atributos da classe pai, alguem pode me ajudar?

victorwss

caloro:
alots_ssa:
Ñão sou muito de indicar frameworks a não ser que realmente queira… Se seu objetivo for aprender reflection pode continuar que é um treino massa, se não, já pensou em considerar o hibernate para fazer este trabalho para vc?

Alberto

Estpu tentando aprender reflection, até de uma lda em hibernate, masi vou deixar pra depois…to meio sem tempo…hehe, mais intaum…estava fazendo o meu metodo e funciona perfeitamente…pra classes que nao herdam de nenhuma outra, masi quando eu tenho uma heranca, eu nao cnsigo pegar os nomes ds atributos da classe pai, alguem pode me ajudar?

minhaClasse.getSuperclass().getMethod("metodoQueEuQuero"); minhaClasse.getSuperclass().getField("atributoQueEuQuero");

Spool

Cara, o primeiro passo é remover esse monte de if´s encadeados.

Procure utilizar o:

if (condicao) {
    // faz algo
} else if (outra_condicao_diferente_da_primeira) {
    // faz outra coisa
} else {
    // senao, faça ainda outra coisa
}

Até!

Criado 5 de outubro de 2008
Ultima resposta 5 de out. de 2008
Respostas 7
Participantes 5