我正在编写一个java应用程序,我有几个java bean(学生,课程,房间等);每个豆子有15到30个田地。 GUI应该提供查看,插入或编辑每个bean的可能性。此外,我有表格显示用户或课程列表等。
有没有一种很好的方法来序列化属性,我不必创建标签和文本字段来插入每个bean的每个属性,但表单是自动生成的?
目前我使用了这个解决方案:
public class User {
public enum UserAttributes{
FirstName (0),
LastName (1),
Address (2);
int index;
private UserAttributes( int index ) {
this.index = index;
}
public int getIndex() {
return index;
}
}
private int numberOfAttributes = UserAttributes.values().length;
private String [] attributes = new String[ numberOfAttributes ];
public void set( UserAttribute a, String value ) {
attribute[ a.getIndex() ] = val;
}
public String get( UserAttribute a ) {
return attribute[ a.getIndex ];
}
}
这样可行,但它会破坏面向对象的范例,而从类图中你看不到类结构。 你认为这是一个优雅的解决方案还是可以有更好的解决方案?
感谢
答案 0 :(得分:0)
这不是您想要的序列化。这是一些代码:
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public final class LearninFormatten
{
enum ValueType
{
FirstName("First Name: ", null),
LastName("Last Name: ", null),
DateOfBirth("Date Of Birth: ", new SimpleDateFormat("dd-MMM-yyyy"));
private Format formatter; // Format definition of this field.
private String label; // Label for this value in the gui.
private ValueType(final String label, final Format formatter)
{
this.formatter = formatter;
this.label = label;
}
/**
* @return The formatter or null.
* null indicates no formatting of the value.
*/
public Format getFormatter()
{
return formatter;
}
public String getLabel()
{
return label;
}
}
final class Value
{
private ValueType valueType;
private Object value;
public Value(final ValueType valueType, final Object value)
{
this.valueType = valueType;
this.value = value;
}
public ValueType getValueType()
{
return valueType;
}
public Object getValue()
{
return value;
}
}
public static void main(String[] args)
{
Calendar calendar = Calendar.getInstance();
LearninFormatten learninFormatten = new LearninFormatten();
Value[] someValues = new Value[3];
calendar.clear();
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.MONTH, 7);
calendar.set(Calendar.DAY_OF_MONTH, 27);
someValues[0] = learninFormatten.new Value(ValueType.FirstName, "Cornelius");
someValues[1] = learninFormatten.new Value(ValueType.LastName, "Snarlington");
someValues[2] = learninFormatten.new Value(ValueType.DateOfBirth, calendar.getTime());
learninFormatten.printValues(someValues);
}
private void printValues(Value[] valueArray)
{
for (Value current : valueArray)
{
Format formatter;
String label;
Object value = current.getValue();
ValueType valueType = current.getValueType();
formatter = valueType.getFormatter();
label = valueType.getLabel();
System.out.print(label);
if (formatter != null)
{
System.out.println(formatter.format(value));
}
else
{
System.out.println(value.toString());
}
}
}
}