package com.java.reflect.database;
public class Customer {
private Long id;
private String username;
private String password;
private String realname;
private String address;
private String email;
private String mobile;
@Override
public String toString() {
return "Customer [id=" + id + ", username=" + username + ", password="
+ password + ", realname=" + realname + ", address=" + address
+ ", email=" + email + ", mobile=" + mobile + "]";
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
public static String saveSql(Object o){
StringBuilder sql = new StringBuilder();
Class c = o.getClass();
sql.append("INSERT INTO ");
Method[] methods = c.getMethods();
String cName = c.getName();
ArrayList<String> fieldNames = new ArrayList<String>();
ArrayList<Object> fieldValues = new ArrayList<Object>();
String tableName = "t_"+cName.substring(cName.lastIndexOf(".")+1,cName.length());
sql.append(tableName);
sql.append(" (");
for(Method method : methods){
String mName = method.getName();
if(mName.startsWith("get") && !mName.startsWith("getClass")){
String fName = "f_"+mName.substring(3);
fieldNames.add(fName);
try{
Object value = method.invoke(o, null);
if(value instanceof String){
fieldValues.add("\""+value+"\"");
}
else{
fieldValues.add(value);
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
for(int i = 0;i<fieldNames.size();++i){
if(i==0){
sql.append(fieldNames.get(i));
}
else{
sql.append(","+fieldNames.get(i));
}
}
sql.append(") values (");
for(int i = 0;i<fieldValues.size();++i){
if(i==0){
sql.append(fieldValues.get(i));
}
else{
sql.append(","+fieldValues.get(i));
}
}
sql.append(")");
return sql.toString();
}