ho cercato di trovare informazioni su questo, ma sono venuto a mani vuote:Creazione di classi in modo dinamico con Java
ho capito, è possibile creare una classe in modo dinamico in Java utilizzando la riflessione o proxy, ma non riesco a trovare fuori Come. Sto implementando un semplice framework di database in cui creo le query SQL utilizzando la reflection. Il metodo ottiene l'oggetto con i campi del database come parametro e crea la query in base a tale. Ma sarebbe molto utile se potessi anche creare l'oggetto stesso dinamicamente in modo da non avere la necessità di avere un semplice oggetto wrapper dati per ogni tabella.
Le classi dinamiche necessiterebbero solo di campi semplici (String
, Integer
, Double
), ad es.
public class Data {
public Integer id;
public String name;
}
E 'possibile e come farei questo?
EDIT: Questo è come vorrei utilizzare questo:
/** Creates an SQL query for updating a row's values in the database.
*
* @param entity Table name.
* @param toUpdate Fields and values to update. All of the fields will be
* updated, so each field must have a meaningful value!
* @param idFields Fields used to identify the row(s).
* @param ids Id values for id fields. Values must be in the same order as
* the fields.
* @return
*/
@Override
public String updateItem(String entity, Object toUpdate, String[] idFields,
String[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ");
sb.append(entity);
sb.append("SET ");
for (Field f: toUpdate.getClass().getDeclaredFields()) {
String fieldName = f.getName();
String value = new String();
sb.append(fieldName);
sb.append("=");
sb.append(formatValue(f));
sb.append(",");
}
/* Remove last comma */
sb.deleteCharAt(sb.toString().length()-1);
/* Add where clause */
sb.append(createWhereClause(idFields, ids));
return sb.toString();
}
/** Formats a value for an sql query.
*
* This function assumes that the field type is equivalent to the field
* in the database. In practice this means that this field support two
* types of fields: string (varchar) and numeric.
*
* A string type field will be escaped with single parenthesis (') because
* SQL databases expect that. Numbers are returned as-is.
*
* If the field is null, a string containing "NULL" is returned instead.
*
* @param f The field where the value is.
* @return Formatted value.
*/
String formatValue(Field f) {
String retval = null;
String type = f.getClass().getName();
if (type.equals("String")) {
try {
String value = (String)f.get(f);
if (value != null) {
retval = "'" + value + "'";
} else {
retval = "NULL";
}
} catch (Exception e) {
System.err.println("No such field: " + e.getMessage());
}
} else if (type.equals("Integer")) {
try {
Integer value = (Integer)f.get(f);
if (value != null) {
retval = String.valueOf(value);
} else {
retval = "NULL";
}
} catch (Exception e) {
System.err.println("No such field: " + e.getMessage());
}
} else {
try {
String value = (String) f.get(f);
if (value != null) {
retval = value;
} else {
retval = "NULL";
}
} catch (Exception e) {
System.err.println("No such field: " + e.getMessage());
}
}
return retval;
}
Non credo che Java è lo strumento giusto per questo, Groovy sarebbe più adatto IMO. –
Personalmente non vedo il problema di avere un modello Java che si associa al modello di database. Inoltre, quando si creano query SQL, assicurarsi di utilizzare PreparedStatements per evitare SQL Injection, anziché creare stringhe SQL. – JeeBee