[Core Java]C5 Reflection

反射的作用

• Analyze the capabilities of classes at runtime;(在运行时获取类的信息)
• Inspect objects at runtime—for example, to write a single toString method that works for all
classes;(通过反射获取field,可以设计所有类通用的toString函数)
• Implement generic array manipulation code; and
• Take advantage of Method objects that work just like function pointers in languages such as C++.(可以实现C++中函数指针的功能)

Class类

获得Class对象的三种方式:

1.通过该类的对象调用getClass()方法获得

Employee e;
. . .
Class cl = e.getClass();

2.通过类名称获得

String className = "java.util.Date";
Class cl = Class.forName(className);

3.import包

Class cl1 = Date.class; // if you import java.util.*;
Class cl2 = int.class;
Class cl3 = Double[].class;

Class对象产生的时间

当一个类或接口被装入的JVM时便会产生一个与之关联的java.lang.Class对象,可以通过这个Class对象对被装入类的详细信息进行访问

反射的几种操作

通过反射获取对象

String s = "java.util.Date";
Object m = Class.forName(s).newInstance();//该函数返回一个Object对象(向上转型),只能调用无参的构造函数

反射获取field,method,constructor

• Field[] getFields() 1.1
• Field[] getDeclaredFields() 1.1
getFields returns an array containing Field objects for the public fields of this class or its
superclasses; getDeclaredField returns an array of Field objects for all fields of this class. The
methods return an array of length 0 if there are no such fields or if the Class object represents
a primitive or array type.
• Method[] getMethods() 1.1
• Method[] getDeclaredMethods() 1.1
returns an array containing Method objects: getMethods returns public methods and includes
inherited methods; getDeclaredMethods returns all methods of this class or interface but does
not include inherited methods.
• Constructor[] getConstructors() 1.1
• Constructor[] getDeclaredConstructors() 1.1
returns an array containing Constructor objects that give you all the public constructors (for
getConstructors) or all constructors (for getDeclaredConstructors) of the class represented by this Class object.

反射实现JDBC中GetById返回对象的动态赋值

子类只要override这个BaseDaoImpl中的getById方法

比如在ProductDaoImpl中定义

public Product getById(int id){

String sql = "select id,name from product(表名) where id = ?";

return super.getById(sql,Product.class);

}

protected T getById(String sql,Object id,Class<T> clazz)
	{
		T model = null;
		Connection conn = null;
		PreparedStatement pre = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			pre = conn.prepareStatement(sql);
			pre.setObject(1, id);//设置SQL语句
			rs = pre.executeQuery();
			
			
			if (rs.next()) {
				//根据class类型动态生成结果集中单个结果的对应实例
				 model = clazz.newInstance();
				 //获得结果的列名称
				 ResultSetMetaData metaData = rs.getMetaData();
				 for (int i = 1; i <= metaData.getColumnCount(); i++) {
					String colName = metaData.getColumnLabel(i);
					Field name = clazz.getDeclaredField(colName);
					name.setAccessible(true);
					//通过反射给相应的属性名称赋值
					name.set(model, rs.getObject(colName));
				}
				 
				 //	model = this.getRow(rs); 这里的this指向当前调用该方法的对象,而不是this位置所在的对象,所以子类override了getById后调用的应该是子类中override的getRow
			}
			return model;
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e); 
		}finally{
			
		}
	}

猜你喜欢

转载自blog.csdn.net/weixin_41985660/article/details/82946536