public static String getUpdate(Object obj) throws IllegalArgumentException, IllegalAccessException{
Class<? extends Object>classll=obj.getClass(); String sql="Update "+classll.getSimpleName()+" set "; String sql2=" "; String sql3=" where "; Field[] field=classll.getDeclaredFields(); for(Field f:field){ f.setAccessible(true); Object value = f.get(obj); if(f.isAnnotationPresent(PrimaryKey.class)){ if(value instanceof String){ sql3 +=f.getName()+"='"+value+"'"; }else{ sql3 +=f.getName()+"="+value+""; } }else if(!f.isAnnotationPresent(NonField.class)){ if(value instanceof String){ sql2 +=f.getName()+"='"+value+"',"; }else{ sql2 +=f.getName()+"="+value+", "; } } } sql2 = sql2.substring(0,sql2.length()-2); sql=sql+sql2+sql3; return sql; }
Userinfo u=new Userinfo();
u.setUsername(" 成都"); u.setUserpwd(" 张山"); u.setUserquan("123"); String userInfoSQL = null; try { userInfoSQL = BeanUtil.getUpdate(u); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(userInfoSQL);
package com.gxa.bj.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)public @interface NonField { }
//通过反射区获取相应的类的一些定义
Class classzz=Person.class; //另外一种获取Class对象的方法 Person p=new Person(); Class classzz2=p.getClass(); System.out.println("类的名称:"+classzz.getSimpleName()); Field[] fields=classzz.getDeclaredFields();//获取定义的字段 for(Field f : fields){ Class c=f.getType();//字段 if(c.getPackage()!=null){ if(c.getPackage().getName().equals("com.gxa.bj.test")){ System.out.println(c.getPackage().getName()); System.out.println("字段类型:"+c.getName()); System.out.println("该字段的名字:"+f.getName()); } } }
public static void main(String[] args) {
// TODO Auto-generated method stub Person p=new Person(); p.setAge(12); p.setName(" 张三 "); Class<? extends Object> classzz = p.getClass(); //通过反射去获取字段的值 Field[] f = classzz.getDeclaredFields(); for(Field field :f){ String methodName="get"+field.getName().substring(0,1).toUpperCase()+field.getName().substring(1); try { Method m=classzz.getDeclaredMethod(methodName); Object o = null; try { o = m.invoke(p); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(o!=null){ System.out.println("方法名:"+methodName+",方法值:"+o); } } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }}