thingol 22 de ago. de 2005
No braço mesmo. Isto deve imprimir “true” “true”.
import java.lang.reflect.* ;
class TestReflection {
public int field1 = 1 ;
public Integer field2 = new Integer ( 2 );
public static void main ( String [] args ) throws Exception {
Class trClass = TestReflection . class ;
Field f1 = trClass . getField ( "field1" );
Field f2 = trClass . getField ( "field2" );
System . out . println ( f1 . getType (). equals ( int . class ));
System . out . println ( f2 . getType (). equals ( Integer . class ));
}
}
passos 22 de ago. de 2005
louds:
System.out.printf("int = %b Integer = %b\n", int.class.isPrimitive(), Integer.class.isPrimitive());
Nao conhecia esse metodos isPrimitive porem não consegui utiliza-lo no meu exemplo:
if ( f . getType () . getClass () . isPrimitive () ) {
System.out.println("Tipo Primitivo : " + f.getType());
}
else {
System.out.println(" Objeto : " + f . getType ());
}
Acho que o que estou fazendo errado e utilizar o getClass pois como disse anteriormente este retorna uma class que e um object Mas nao estou conseguindo ver uma maneira de fazer o que quero!
thingol 22 de ago. de 2005
Obrigadão Louds, não sabia que havia esse método (eu não li a P… do Javadoc :mrgreen: )
Então dá para modificar (vai imprimir “true false”):
import java.lang.reflect.* ;
class TestReflection {
public int field1 = 1 ;
public Integer field2 = new Integer ( 2 );
public static void main ( String [] args ) throws Exception {
TestReflection tr = new TestReflection ();
Class trClass = TestReflection . class ;
Field f1 = trClass . getField ( "field1" );
Field f2 = trClass . getField ( "field2" );
System . out . println ( f1 . getType (). isPrimitive ());
System . out . println ( f2 . getType (). isPrimitive ());
}
}
Note que NÃO HÁ NENHUM instanceof neste código aqui.