Menu

#200 Enhancement for Java Generics

V2 beta
open
nobody
engine (145)
5
2013-01-25
2013-01-25
Anonymous
No

An enhancement needs to be made to org.neodatis.odb.core.query.nq.NativeQueryManager and NativeQuery for better Java Generics support as follow:

1. NativeQuery
public abstract class NativeQuery<T>{
private final Class<T> type;

public NativeQuery(Class<T> type){
this.type = type;
}

public Class<T> getType() {
return type;
}
}

2. org.neodatis.odb.core.query.nq.NativeQueryManager
public static String getFullClassName(NativeQuery query){
Class clazz = null;
Method[] methods = OdbReflection.getMethods(query.getClass());

for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
Class[] attributes = OdbReflection.getAttributeTypes(method);
//if (method.getName().equals(MATCH_METHOD_NAME) && attributes.length==1 && attributes[0]!=Object.class){
if (method.getName().equals(MATCH_METHOD_NAME) && attributes.length==1){
//clazz = attributes[0];
clazz = query.getType() != null ? query.getType() : attributes[0];
if(clazz == Object.class) continue;
method.setAccessible(true);
methodsCache.put(query,method);
return clazz.getName();
}
}
throw new NeoDatisRuntimeException(NeoDatisError.QUERY_NQ_MATCH_METHOD_NOT_IMPLEMENTED.addParameter(query.getClass().getName()));
}

The reason for this can be seen in the example below (note the outputs):
package com.tchegbe.db.update;

import java.lang.reflect.Method;

public class Test {
public static class MyClass{};

public static interface NativeQuery<T>{
public boolean match(T object);
};

public static <T> NativeQuery<T> get(Class<T> clazz){
return new NativeQuery<T>() {
@Override
public boolean match(T object) {
return false;
}
};
}

public static void main(String[] args) {
try {
NativeQuery<MyClass> q1 = new NativeQuery<MyClass>() {
@Override
public boolean match(MyClass object) {
return false;
}
};
NativeQuery<MyClass> q2 = get(MyClass.class);
System.out.println("%%%%%%%%%%%%%%%%%%%%%%% Test1 %%%%%%%%%%%%%%%%%%%%%%%%%%");
print(q1);
System.out.println("%%%%%%%%%%%%%%%%%%%%%%% Test2 %%%%%%%%%%%%%%%%%%%%%%%%%%");
print(q2);

} catch (Exception e) {
e.printStackTrace();
}
}

private static <T> void print(NativeQuery<T> q){
Method[] methods = q.getClass().getDeclaredMethods();

for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
Class<?>[] attributes = method.getParameterTypes();
StringBuilder sb = new StringBuilder();
sb.append(method.getName()).append('(');
if(attributes != null && attributes.length > 0){
sb.append(attributes[0].getName());
for(int j=1; j<attributes.length; j++){
sb.append(", ").append(attributes[j].getName());
}
}
sb.append(')');

System.out.println(sb.toString());
}
}
}

OUTPUT:
%%%%%%%%%%%%%%%%%%%%%%% Test1 %%%%%%%%%%%%%%%%%%%%%%%%%%
match(com.tchegbe.db.update.Test$MyClass)
match(java.lang.Object)
%%%%%%%%%%%%%%%%%%%%%%% Test2 %%%%%%%%%%%%%%%%%%%%%%%%%%
match(java.lang.Object)

Discussion


Log in to post a comment.