PDA

View Full Version : how to use reflect



q1111
1 Apr 2011, 7:06 PM
sorry to my poor english. the problem like this:
1.public class HspEvents {
public static final EventType ADD_INIT = new EventType ();
public static final EventType ADD_VALIDATE = new EventType ();
}
2.Dispatcher.get ().dispatch(HspEvents.ADD_INIT , model);
I want to change it to:
Dispatcher.get ().dispatch(CenterEvents.getEvent("ADD_INIT "), model);
3.so i write a class
import java.lang.reflect.Field;
import com.extjs.gxt.ui.client.event.EventType;
import com.supcon.center.hsp.client.mvc.events.HspEvents;
import com.supcon.center.security.client.mvc.events.SecurityEvents;
public class CenterEvents {
public CenterEvents() {
}

public static EventType getEvent(String eventName) {
EventType temp = new EventType();

try{
Class[] classes = {SecurityEvents.class, HspEvents.class};
for(Class c : classes){
Field[] fields = c.getFields();
for(Field f : fields){
String name = f.getName();
if(name.trim().equals(eventName.trim())){

temp = (EventType)f.get(eventName);
}
}
}
} catch(Exception e){
return null;
}

return temp;
}
}

the problem is :gxt cannot use java.lang.reflect

another method to resolve the EventType is:
public class HspEvents {
public static final EventType ADD_INIT = new EventType ();
public static final EventType ADD_VALIDATE = new EventType ();

public static Map <String, EventType> GLOBALS_EVENT = new HashMap <String, EventType> ();
public static void init ()
{
GLOBALS_EVENT.put ("ADD_INIT ", ADD_INIT );
GLOBALS_EVENT.put ("ADD_VALIDATE ", ADD_VALIDATE );
}

public static EventType getEventType (String event) {
init ();
EventType eventType = GLOBALS_EVENT.get (event);
return eventType;
}
}

but i think it is not a good idea. so how can i do it simplely?