Ref.: Membros de uma classe

13 respostas
P

Boa!

Estou precisando mostrar todos os membros de uma classe e seus respativos tipos.

Algo tipo isso:

Public Function LeColunasTabela(ByVal objTabela As Object) As Array
        Dim arrCamposValores(,) As Object
        Dim MyType As Type = Type.GetType(objTabela.ToString)
        Dim Mypropertyinfoarray As PropertyInfo() = MyType.GetProperties()

        'Dimensiona array
        arrCamposValores = New Object(Mypropertyinfoarray.GetLength(0) - 1, 2) {}

        For intContadorPropriedades As Integer = 0 To Mypropertyinfoarray.GetLength(0) - 1
            'Recebe nome da propriedade
            arrCamposValores(intContadorPropriedades, 0) = Mypropertyinfoarray(intContadorPropriedades).Name

            'Recebe valor da propriedade
            arrCamposValores(intContadorPropriedades, 1) = Mypropertyinfoarray(intContadorPropriedades).GetValue(objTabela, Nothing)
        Next intContadorPropriedades

        Return arrCamposValores
    End Function

Desenvolvi várias paradas para agilizar o desenvolvimento, agora preciso implementa-las no JAVA.

Quem pode me ajudar?

13 Respostas

P

ESTOU Quase lá!

Vejam:

Usuario u = new Usuario();

        Class theClass;
        try {
            theClass = Class.forName(u.getClass().getName());
            Field fields[] = theClass.getDeclaredFields();
            for (int j = 0, m = fields.length; j &lt m; j++) {
                System.out.println(fields[j].getName() + ", " +
                                   fields[j].getType().getName() + ", " + 
                                   Modifier.toString(fields[j].getModifiers()));
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }

Sabendo o que se deseja, e com muito vontade de fazer-lo, o CARA nos ajuda.

kaoe

Só uma observação, este trecho fica meio sem sentido

theClass = Class.forName(u.getClass().getName());

Considerando que u.getClass() é um objeto Class use algo como

theClass = u.getClass();
P

Porra!

Sabe que não tinha pensado nisso!

É que quando estamos tentanto é assim mesmo.

Contudo: Várias cabeças pensam melhor.

Valeu!

P

Agora preciso pegar o VALOR de cada Membro GET

Quem pode me ajudar?

Usuario u = new Usuario();
        u.setDataCadastramento(new GregorianCalendar(2007, 05, 14));
        u.setNome("Paulo Roberto");
        
        Class theClass;
        theClass = u.getClass();
        
        System.out.println("-------------- Campos --------------");
        //Campos
        Field fields[] = theClass.getDeclaredFields();
        for (int j = 0, m = fields.length; j &lt m; j++) {
            System.out.println(fields[j].getName() + ", " +
                    fields[j].getType().getName() + ", " +
                    Modifier.toString(fields[j].getModifiers()));
        }
        
        System.out.println("------------- Métodos -------------");
        //Métodos
        Method methods[] = theClass.getDeclaredMethods();
        for (int j = 0, m = methods.length; j &lt m; j++) {
            if (methods[j].getName().substring(0, 3).equals("get")) {
                System.out.println(methods[j].getName() + ", " +
                        methods[j].getDefaultValue() + ", " +
                        Modifier.toString(methods[j].getModifiers()));
            }
        }
        
        System.out.println("------------- Métodos 2 -------------");
        try {
            Class c = Class.forName(u.getClass().getName());
            Method m[] = c.getDeclaredMethods();
            for (int i = 0; i &lt m.length; i++)
                System.out.println(m[i].toString());
        } catch (Throwable e) {
            System.err.println(e);
        }
F

System.out.println("------------- Métodos 3 -------------"); try { Class c = u.getClass(); Method m[] = c.getDeclaredMethods(); for (int i = 0; i < m.length; i++){ //Só invoca o método se o retorno for diferente de void e não possuir parametros if(!m[i].getReturnType().equals(Void.class) && m[i].getParameterTypes().length <= 0){ Object value = m[i].invoke(u, new Object[0]); System.out.println(value); } } } catch (Throwable e) { System.err.println(e); }

Flw

P

Boa tarde a todos.

Voltei depois de quase quinze dias sem máq., agora preciso retomar meu trabalho.

Ainda continuo precisando OBTER o valor de cada uma das propriedades.

Quem pode me ajudar?

F

Esta no meu post do dia 29 logo acima.

P

Muito obrigado FRED, pois só depois que enviei que ví.

Portanto, quando se trata disso:

u.setDataCadastramento(new GregorianCalendar(2007, 05, 14));

Veja o que ele mostra.

System.out.println("------------- Métodos 3 -------------");
      try {
          Class c = u.getClass();
          Method m[] = c.getDeclaredMethods();
          for (int i = 0; i &lt m.length; i++){
         	 // invoca o método se o retorno for diferente de void e não possuir parametros
         	 if(!m[i].getReturnType().equals(Void.class) && m[i].getParameterTypes().length &lt= 0){
         		 Object value = m[i].invoke(u, new Object[0]);
         		 System.out.println(m[i].getName() + " - " + value);
         	 }
          }
      } catch (Throwable e) {
          System.err.println(e);
      }

Aproveitando o ensejo:

Resolvido isto, preciso criar uma ARRAY MUltidimensional dinâmico. para receber os Métodos e seus Repectivos valores.

Pode me ajudar?

P

Depois que tudo estiver pronto, disponibilizarei ao grupo, nossos dias serão maiores depois disso.

'CLEIO EU!"

P

Isto tudo é para ser usado aqui:

/*
 * ManutencaoTabela.java
 *
 * Created on 23 de Junho de 2007, 21:01
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package bancodados;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;

/**
 *
 * @author Paulo Roberto
 */
public class ManutencaoTabela {
    public void IncluiRegistro(final Object Tabela, final String NomeTabela, final Connection Conexao) {
        //
    }
    
    public void AtualizaRegistro(final Object Tabela, final String NomeTabela, final Connection Conexao) {
        //
    }
    
    public void ExcluiRegistro(final Object Tabela, final String NomeTabela, final Connection Conexao) {
        //
    }

    public void ExecutaTransacao(final String sbSQL, final Connection Conexao) {
        try {
            //Prepara transação
            PreparedStatement pstmt = Conexao.prepareStatement(sbSQL.toString());
            //Executa  procedimento
            pstmt.executeUpdate();
            //Consolida transação
            Conexao.commit();
            //Fecha procedimento
            pstmt.close();
            //Fecha conexão
            Conexao.close();
            //Mostra String SQL
            System.out.println(sbSQL);
        } catch (SQLException errorSQL) {
            JOptionPane.showMessageDialog(null, errorSQL.getMessage(), "Erro SQL", JOptionPane.ERROR_MESSAGE);
            errorSQL.printStackTrace();
        }
    }

    public void PreparaInclusao(final Object Tabela, final String NomeTabela) {
    }

    public void LeColunasTabela(final Object Tabela) {
////        class Fill3DArray {
////
////          public static void main (String args[]) {
////
////            int[][][] M;
////            M = new int[4][5][3];
////
////            for (int row=0; row &lt 4; row++) {
////              for (int col=0; col &lt 5; col++) {
////                for (int ver=0; ver &lt 3; ver++) {
////                  M[row][col][ver] = row+col+ver;
////                }
////              }
////            }
////
////          }
////
////        }
        
        //
        int [][] CamposValores;
        CamposValores = new int[0][0];
               
        CamposValores[0][0] = 0;
        CamposValores[0][1] = 1;
        CamposValores[0][2] = 2;
        CamposValores[0][3] = 3;
        CamposValores[0][4] = 4;
        CamposValores[1][0] = 00;
        CamposValores[1][1] = 11;
        CamposValores[1][2] = 22;
        CamposValores[1][3] = 33;
        CamposValores[1][4] = 44;
        
        //
        ArrayList alCamposValores = new ArrayList();
    
        alCamposValores.add(0, Tabela);
    }
}

O ALVO por enquanto é "LeColunasTabela"

F

Pesquise como se utiliza a classe HashMap.

public HashMap getPropriedadeValor(final Object tabela){

HashMap propriedadeValor = new HashMap();
	try {
		Class c = tabela.getClass();
		Method m[] = c.getDeclaredMethods();
		for (int i = 0; i < m.length; i++) {
			if (!m[i].getReturnType().equals(Void.class) && m[i].getParameterTypes().length <= 0) {
				Object value = m[i].invoke(tabela, new Object[0]);
				propriedadeValor.put(m[i].getName(), value);
			}
		}
	} catch (Throwable e) {
		System.err.println(e);
	}
	return propriedadeValor;
}

o resultado para uma classe Usuario com propriedade nome vai ficar assim

chave=getNome valor=fred

Fred

P

OK Fred. Teei que dar uma saida agora, mas volto daqui a duas horas.

Irei testar.

Acha que vai ficar legal isso que estou tentando fazer?

Se preferir use MSN ([email removido])

Valeu!

JMan

Reflection é a solução para todos os seus problemas!!!

http://java.sun.com/docs/books/tutorial/reflect/index.html

Criado 28 de junho de 2007
Ultima resposta 28 de jun. de 2007
Respostas 13
Participantes 4