1.反射
一种计算机处理方式。是程序可以访问、检测和修改它本身状态或行为的一种能力。
新建一个Person类:
public class Person { private int age; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Person(){}private Job job; public Job getJob() { return job; } public void setJob(Job job) { this.job = job; } }
2.再建一个测试类:
public class TestUI {public static void main(String[] args) {Class classzz = Person.class;Field[] fields = classzz.getDeclaredFields();for(Field f:fields){Class c = f.getType();if(c.getPackage()!=null){if(c.getPackage().getName().equals("com.Test")){//筛选出Job类System.out.println(c.getPackage().getName());System.out.println("字段的类型:"+c.getName());System.out.println("该字段的名字:"+f.getName());}}}String userInfoSQL = BeanUtil.getSelect(new UserInfo());System.out.println(userInfoSQL);} }
3.新建一个Job类:
public class Job {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;} }
4.BeanUtil类的内容
public class BeanUtil {public static String getSelect(Object obj){Class classzz = obj.getClass();String TableName = classzz.getSimpleName();StringBuffer sql = new StringBuffer();sql.append("Select * from "+TableName+" ");return sql.toString();} }
5.显示结果:
com.Test
字段的类型:com.Test.Job
该字段的名字:job
Select * from UserInfo//提取出BeanUtil里的sql语句