java-org.hwo/src/org/hwo/models/Column.java

133 lines
2.9 KiB
Java

package org.hwo.models;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Column {
private int MODE_FIELD = 1;
private int MODE_GETSET = 2;
private int mode;
private String fieldName;
private boolean readonly;
private Class p_class;
private Field field;
private Method getter;
private Method setter;
public Column(Class classInfo,String fieldName,boolean readonly) throws NoSuchFieldException
{
this.fieldName = fieldName;
this.readonly = readonly;
this.p_class = classInfo;
this.getter = null;
this.setter = null;
try
{
mode = MODE_FIELD;
this.field = this.p_class.getDeclaredField(fieldName);
this.field.setAccessible(true);
} catch (NoSuchFieldException nsfex)
{
mode = MODE_GETSET;
// Kein deklariertes Feld, also suchen wir eine get... und set... Methode...
Method[] methods = this.p_class.getDeclaredMethods();
for (Method method : methods) {
// passender getter?
if (("get"+fieldName.toLowerCase()).equals(method.getName().toLowerCase()))
getter = method;
// passender setter?
if (("set"+fieldName.toLowerCase()).equals(method.getName().toLowerCase()))
setter = method;
}
if (getter == null)
throw nsfex;
}
}
public String getFieldName()
{
return this.fieldName;
}
public boolean getReadOnly()
{
if ((mode == MODE_GETSET) && (setter == null))
return true;
return this.readonly;
}
public void setReadOnly(boolean readOnly)
{
this.readonly = readOnly;
}
public Class getColumnClass()
{
if (mode == MODE_GETSET)
return this.getter.getReturnType();
return this.field.getType();
}
Object getValue(Object o)
{
try
{
if (mode == MODE_GETSET)
{
try
{
Object ro = this.getter.invoke(o, null);
return ro;
} catch (InvocationTargetException itex)
{
System.err.println(itex.toString());
itex.printStackTrace();
}
}
return this.field.get(o);
} catch (IllegalArgumentException e) {
System.err.println("IllegalArgument! " + e.toString());
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
System.err.println("IllegalAccess! " + e.toString());
e.printStackTrace();
}
return null;
}
void setValue(Object o,Object value)
{
try
{
if (mode == MODE_GETSET)
{
if (this.setter != null)
{
try
{
this.setter.invoke(o,new Object[]{ value });
} catch (InvocationTargetException itex)
{
System.err.println(itex.toString());
itex.printStackTrace();
}
}
}
this.field.set(o,value);
} catch (IllegalArgumentException e) {
System.err.println("IllegalArgument! " + e.toString());
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
System.err.println("IllegalAccess! " + e.toString());
e.printStackTrace();
}
return;
}
}