Once loved watching a comic old movie, where a clause was often said:"what's in this ring box ?" accompanied with a surprising answer:"an elephant is in this ring box " :o
Reflection discover whats in the black box "an object", could know what is in an object as if a mirror that reflects it content "ability to examine the run-time properties of the object "
small ex
wanted to return a generic list containing result of a sql query "as if hibernate"
List<T>list=new ArrayList<T>();
ResultSetMetaData metadata=resultSet.getMetaData();
String[] columnName=new String[metadata.getColumnCount()];
for(int i=0;i<columnName.length;i++){//column name equivalent to object instance variable
columnName[i]=metadata.getColumnLabel(i+1);
}
int index=0;
T t;
while (resultSet.next()) {
list.add((T)cls.newInstance());
t=list.get(index);
for(int i=0;i<columnName.length;i++){//initialization
Method setMethod=t.getClass().getDeclaredMethod("set"+columnName[i],String.class);
setMethod.invoke(t, resultSet.getString(columnName[i]));//invoking object method to init-
}
index++;
}
Reflection discover whats in the black box "an object", could know what is in an object as if a mirror that reflects it content "ability to examine the run-time properties of the object "
small ex
wanted to return a generic list containing result of a sql query "as if hibernate"
List<T>list=new ArrayList<T>();
ResultSetMetaData metadata=resultSet.getMetaData();
String[] columnName=new String[metadata.getColumnCount()];
for(int i=0;i<columnName.length;i++){//column name equivalent to object instance variable
columnName[i]=metadata.getColumnLabel(i+1);
}
int index=0;
T t;
while (resultSet.next()) {
list.add((T)cls.newInstance());
t=list.get(index);
for(int i=0;i<columnName.length;i++){//initialization
Method setMethod=t.getClass().getDeclaredMethod("set"+columnName[i],String.class);
setMethod.invoke(t, resultSet.getString(columnName[i]));//invoking object method to init-
}
index++;
}
Comments
Post a Comment