1 反射技术2 Class对象3 Field类
3.1 例子 4 Method类5 反射的应用 1 反射技术
2 Class对象运行时动态访问对象属性方法的技术
类的实例化:
之前:Car c = new Car();
现在:clazz.newInstance(); // 创建对象
public class ClassDemo {static class InnerClass{public InnerClass() {System.out.println("我是InnerClass构造方法");}public void print() {System.out.println("我是静态内部类");}}public static void main(String[] args) throws InstantiationException, IllegalAccessException {Class
3.1 例子描述类中的属性,(数值)域
public class FiledDemo {static class Car {private String brand;private String color;private double price;public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}@Overridepublic String toString() {return "Car [brand=" + brand + ", color=" + color + ", price=" + price + "]";}}public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {Car c = new Car();c.setBrand("奇瑞QQ");c.setColor("蓝色");c.setPrice(20000.00);System.out.println(c);// 通过反射技术可以拿到private修饰的属性Class
public class MethodDemo {static class Car {private String brand;private String color;private double price;public void run() {System.out.println("汽车发动");}public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}@Overridepublic String toString() {return "Car [brand=" + brand + ", color=" + color + ", price=" + price + "]";}}public static void main(String[] args) throws Exception {Car c = new Car();c.setBrand("奇瑞QQ");c.setColor("蓝色");c.setPrice(20000.00);System.out.println(c);// c.run();// 大部分情况下,是创建对象后调用run()方法// 用反射的方法调用run()方法Class
用反射技术自动生成sql语句
public class SQLHelper {private static volatile SQLHelper instance;private final StringBuilder sb = new StringBuilder();private SQLHelper() {}public static SQLHelper getInstance() {if (instance == null) {synchronized (SQLHelper.class) {if (instance == null) {instance = new SQLHelper();}}}return instance;}public String createInsertSQL(Object obj) {Class<?> clazz = obj.getClass();Field[] fields = clazz.getDeclaredFields();sb.append("INSERT INTO ");String tableName = clazz.getSimpleName().toLowerCase();sb.append(tableName);sb.append("(");int count = 0;try {for (Field field : fields) {field.setAccessible(true);Object retval = field.get(obj);if (retval != null) {// 有值,准备放入数据库sb.append(tableName + "_" + field.getName());sb.append(",");count++;}}sb.deleteCharAt(sb.length() - 1);sb.append(") VALUES(");for(int i = 0 ; i < count ; i ++) {sb.append("?,");}sb.deleteCharAt(sb.length() - 1);sb.append(")");} catch (Exception e) {e.printStackTrace();}return sb.toString();}}