首页 > 代码库 > 通用类的写法

通用类的写法

package com.icss.hr.job.dao;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.icss.hr.job.pojo.AbstractObj;
import com.icss.hr.job.pojo.Job;

@Repository
public class DaoImpl implements IDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Test
	public void test() throws Exception{   
		ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
		IDao dao =(DaoImpl)ac.getBean("daoImpl");
		Job obj = new Job("jb001","java初级程序员",4000,8000);		
		dao.add(obj);
	}
	

	@Override
	public boolean add(AbstractObj obj) throws Exception {  //这是重点,后期讲课时,让学生把反射这块死练,让他们记得滚瓜烂熟为止
		StringBuilder sb=new StringBuilder();
		
		sb.append("insert into ")
		  .append(obj.getClass().getSimpleName())
		  .append(" values (");
		
		Field[] f = obj.getClass().getDeclaredFields();//获取所有的属性
				
		String str=null;
		Object[] value=http://www.mamicode.com/new Object[f.length];//存放方法返回值"?,");
			String s=f[i].getName().substring(0,1).toUpperCase();
			String s2=f[i].getName().substring(1,f[i].getName().length());
			str="get"+s+s2;
			Method m=obj.getClass().getMethod(str); //根据方法名获得的方法对象 
			value[i]=m.invoke(obj);//根据对象类型而执行的方法,结果是方法返回值
		} 
		String sql=sb.substring(0,sb.length()-1).toString()+")";		
		System.out.println("sql:  "+sql);
		System.out.println("value:  "+Arrays.toString(value));
		
		int rows = jdbcTemplate.update(sql,value);		
		return rows>0;
	}


	@Override
	public boolean update(AbstractObj obj) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean delete(int _id) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public List<AbstractObj> queryAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public AbstractObj queryById(int id) {
		// TODO Auto-generated method stub
		return null;
	}



}

  

通用类的写法