Pegar ID (primary key) usando Reflection

5 respostas
d34d_d3v1l

Galera, estou apanhando para Generics (Reflection)… Estou tentando fazer duas coisas…

Primeiro: pegar o tipo da classe da chave primária, para depois fazer um casting de String pra ela
Segundo: retornar o valor da chave primaria

Mas o código que eu fiz ta meio suspeito…
Alguém consegue me ajudar

protected Class<?> getPrimaryKeyDeclaringClass(){
		   Class<?> type = entity.getClass();
		   
		    for (Field f : type.getDeclaredFields()) {
		        if (f.getAnnotation(Id.class) != null) {
		        	return f.getDeclaringClass();
		        }
		    }
		    
		    return null;		
	}



			//FIX-ME need to change this :(
			@SuppressWarnings("unchecked")
			@Override
			public T getRowData(String key) {				
				return getBaseService().findOne(  (PK) getPrimaryKeyDeclaringClass().cast(key) );
			}
			
			
			@SuppressWarnings("unchecked")
			@Override
			public Object getRowKey(T obj) {
				   PK id = null;
				   Class<?> type = obj.getClass();
				   
				    for (Field f : type.getDeclaredFields()) {
				        if (f.getAnnotation(Id.class) != null) {
				            String name = f.getName();
				            String method = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
				            try {
				                Method m = type.getDeclaredMethod(method, (Class<?>) null);
				                id = (PK) m.invoke(obj, (Object []) null);
				            } catch (Exception e) {
				                e.printStackTrace();
				            }
				        }
				    }
				    
				    return id;
			}

5 Respostas

mauriciot.silva

Bom amigo aki esta eu codigo

protected Class<?> getPrimaryKeyDeclaringClass(Class<?> entity) {

		for (Field f : entity.getDeclaredFields()) {
			if (f.isAnnotationPresent(Id.class)) {
				return f.getType();
			}
		}

		return null;
	}

	// FIX-ME need to change this :(
	public static Object getRowData(Class<?> entity, Object key) {
		return getPrimaryKeyDeclaringClass(entity).cast(key);
	}

	public Object getRowKey(Object obj) {
		Object id = null;
		Class<?> type = obj.getClass();

		for (Field f : type.getDeclaredFields()) {
			if (f.isAnnotationPresent(Id.class)) {
				String name = f.getName();
				String method = "get" + name.substring(0, 1).toUpperCase()
						+ name.substring(1);
				try {
					Method m = type.getDeclaredMethod(method);
					id = (Object) m.invoke(obj);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return id;
	}

dei uma adaptada para fazer alguns teste ...
OBS: para chave composta nao esta muito bem...
O Cast Exception era por conta de quando vs pega o Field tem q pegar o tipo da chave (Long, String..)
field getAnnotation() != null unnnhhh, usa isAnnotationPresent..

E a duvida eh de reflection e nao generics
espero ter ajudado

d34d_d3v1l

valeuu!

algumas modificações eu nao posso fazer
pois estou sobrescrevendo metodos de uma interface =[[

mas acho que agora da para continuar… :slight_smile:

isAnnotationPresent realmente muito mais elegante kkkkkkkkkkk boa dica!!! :slight_smile:

qndo testar eu falo aqui e ‘fecho’ o post :slight_smile:

vlwwww

d34d_d3v1l
java.lang.ClassCastException: Cannot cast java.lang.String to java.lang.Integer

ta retornando o tipo certo, mas não consegue fazer o cast

@SuppressWarnings("unchecked") @Override public T getRowData(String key) { return getBaseService().findOne( (PK) getPrimaryKeyDeclaringClass().cast(key) ); }

sugestoes?

mauriciot.silva

Se ao inver de vs receber um java.lang.String receba um Objct…

d34d_d3v1l

não posso cara…

@Override

:frowning:

Criado 28 de outubro de 2012
Ultima resposta 28 de out. de 2012
Respostas 5
Participantes 2