java反射

【案例1】通过一个对象获得完整的包名和类名

package Reflect;

 

/**

 * 通过一个对象获得完整的包名和类名

 * */

class Demo{

    //other codes...

}

 

class hello{

    public static void main(String[] args) {

        Demo demo=new Demo();

        System.out.println(demo.getClass().getName());

    }

}

【运行结果】:Reflect.Demo

添加一句:所有类的对象其实都是Class的实例。

【案例2】实例化Class类对象

package Reflect;

class Demo{

    //other codes...

}

 

class hello{

    public static void main(String[] args) {

        Class<?> demo1=null;

        Class<?> demo2=null;

        Class<?> demo3=null;

        try{

            //一般尽量采用这种形式

            demo1=Class.forName("Reflect.Demo");

        }catch(Exception e){

            e.printStackTrace();

        }

        demo2=new Demo().getClass();

        demo3=Demo.class;

         

        System.out.println("类名称   "+demo1.getName());

        System.out.println("类名称   "+demo2.getName());

        System.out.println("类名称   "+demo3.getName());

         

    }

}

【运行结果】:

类名称   Reflect.Demo

类名称   Reflect.Demo

类名称   Reflect.Demo

【案例3】通过Class实例化其他类的对象

通过无参构造实例化对象

package Reflect;

 

class Person{

     

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public int getAge() {

        return age;

    }

    public void setAge(int age) {

        this.age = age;

    }

    @Override

    public String toString(){

        return "["+this.name+"  "+this.age+"]";

    }

    private String name;

    private int age;

}

 

class hello{

    public static void main(String[] args) {

        Class<?> demo=null;

        try{

            demo=Class.forName("Reflect.Person");

        }catch (Exception e) {


            e.printStackTrace();

        }

        Person per=null;

        try {

            per=(Person)demo.newInstance();

        } catch (InstantiationException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        } catch (IllegalAccessException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

        per.setName("Rollen");

        per.setAge(20);

        System.out.println(per);

    }

}

【运行结果】:

[Rollen  20]

但是注意一下,当我们把Person中的默认的无参构造函数取消的时候,比如自己定义只定义一个有参数的构造函数之后,会出现错误:

比如我定义了一个构造函数:

public Person(String name, int age) {

        this.age=age;

        this.name=name;

    }

然后继续运行上面的程序,会出现:

java.lang.InstantiationException: Reflect.Person

    at java.lang.Class.newInstance0(Class.java:340)

    at java.lang.Class.newInstance(Class.java:308)

    at Reflect.hello.main(hello.java:39)

Exception in thread "main" java.lang.NullPointerException

    at Reflect.hello.main(hello.java:47)

所以大家以后再编写使用Class实例化其他类的对象的时候,一定要自己定义无参的构造函数

【案例】通过Class调用其他类中的构造函数 (也可以通过这种方式通过Class创建其他类的对象)

package Reflect;

 

import java.lang.reflect.Constructor;

 

class Person{

     

    public Person() {

         

    }

    public Person(String name){

        this.name=name;

    }

    public Person(int age){

        this.age=age;

    }

    public Person(String name, int age) {

        this.age=age;

        this.name=name;

    }

    public String getName() {

        return name;

    }

    public int getAge() {

        return age;

    }

    @Override

    public String toString(){

        return "["+this.name+"  "+this.age+"]";

    }

    private String name;

    private int age;

}

 

class hello{

    public static void main(String[] args) {

        Class<?> demo=null;

        try{

            demo=Class.forName("Reflect.Person");

        }catch (Exception e) {

            e.printStackTrace();

        }

        Person per1=null;

        Person per2=null;

        Person per3=null;

        Person per4=null;

        //取得全部的构造函数

        Constructor<?> cons[]=demo.getConstructors();

        try{

            per1=(Person)cons[0].newInstance();

            per2=(Person)cons[1].newInstance("Rollen");

            per3=(Person)cons[2].newInstance(20);

            per4=(Person)cons[3].newInstance("Rollen",20);

        }catch(Exception e){

            e.printStackTrace();

        }

        System.out.println(per1);

        System.out.println(per2);

        System.out.println(per3);

        System.out.println(per4);

    }

}

【运行结果】:

[null  0]

[Rollen  0]

[null  20]

[Rollen 20]

【案例】

返回一个类实现的接口

package Reflect;

 

interface China{

    public static final String name="Rollen";

    public static  int age=20;

    public void sayChina();

    public void sayHello(String name, int age);

}

 

class Person implements China{

    public Person() {

         

    }

    public Person(String sex){

        this.sex=sex;

    }

    public String getSex() {

        return sex;

    }

    public void setSex(String sex) {

        this.sex = sex;

    }

    @Override

    public void sayChina(){

        System.out.println("hello ,china");

    }

    @Override

    public void sayHello(String name, int age){

        System.out.println(name+"  "+age);

    }

    private String sex;

}

 

class hello{

    public static void main(String[] args) {

        Class<?> demo=null;

        try{

            demo=Class.forName("Reflect.Person");

        }catch (Exception e) {

            e.printStackTrace();

        }

        //保存所有的接口

        Class<?> intes[]=demo.getInterfaces();

        for (int i = 0; i < intes.length; i++) {

            System.out.println("实现的接口   "+intes[i].getName());

        }

    }

}

【运行结果】:

实现的接口   Reflect.China

(注意,以下几个例子,都会用到这个例子的Person类,所以为节省篇幅,此处不再粘贴Person的代码部分,只粘贴主类hello的代码)

【案例】:取得其他类中的父类

class hello{

    public static void main(String[] args) {

        Class<?> demo=null;

        try{

            demo=Class.forName("Reflect.Person");

        }catch (Exception e) {

            e.printStackTrace();

        }

        //取得父类

        Class<?> temp=demo.getSuperclass();

        System.out.println("继承的父类为:   "+temp.getName());

    }

}

【运行结果】

继承的父类为:   java.lang.Object

【案例】:获得其他类中的全部构造函数

这个例子需要在程序开头添加import java.lang.reflect.*;

然后将主类编写为:

class hello{

    public static void main(String[] args) {

        Class<?> demo=null;

        try{

            demo=Class.forName("Reflect.Person");

        }catch (Exception e) {

            e.printStackTrace();

        }

        Constructor<?>cons[]=demo.getConstructors();

        for (int i = 0; i < cons.length; i++) {

            System.out.println("构造方法:  "+cons[i]);

        }

    }

}

【运行结果】:

构造方法:  public Reflect.Person()

构造方法:  public Reflect.Person(java.lang.String)

但是细心的读者会发现,上面的构造函数没有public 或者private这一类的修饰符

下面这个例子我们就来获取修饰符

class hello{

    public static void main(String[] args) {

        Class<?> demo=null;

        try{

            demo=Class.forName("Reflect.Person");

        }catch (Exception e) {

            e.printStackTrace();

        }

        Constructor<?>cons[]=demo.getConstructors();

        for (int i = 0; i < cons.length; i++) {

            Class<?> p[]=cons[i].getParameterTypes();

            System.out.print("构造方法:  ");

            int mo=cons[i].getModifiers();

            System.out.print(Modifier.toString(mo)+" ");

            System.out.print(cons[i].getName());

            System.out.print("(");

            for(int j=0;j<p.length;++j){

                System.out.print(p[j].getName()+" arg"+i);

                if(j<p.length-1){

                    System.out.print(",");

                }

            }

            System.out.println("){}");

        }

    }

}

【运行结果】:

构造方法:  public Reflect.Person(){}

构造方法:  public Reflect.Person(java.lang.String arg1){}

有时候一个方法可能还有异常,呵呵。下面看看:

class hello{

    public static void main(String[] args) {

        Class<?> demo=null;

        try{

            demo=Class.forName("Reflect.Person");

        }catch (Exception e) {

            e.printStackTrace();

        }

        Method method[]=demo.getMethods();

        for(int i=0;i<method.length;++i){

            Class<?> returnType=method[i].getReturnType();

            Class<?> para[]=method[i].getParameterTypes();

            int temp=method[i].getModifiers();

            System.out.print(Modifier.toString(temp)+" ");

            System.out.print(returnType.getName()+"  ");

            System.out.print(method[i].getName()+" ");

            System.out.print("(");

            for(int j=0;j<para.length;++j){

                System.out.print(para[j].getName()+" "+"arg"+j);

                if(j<para.length-1){

                    System.out.print(",");

                }

            }

            Class<?> exce[]=method[i].getExceptionTypes();

            if(exce.length>0){

                System.out.print(") throws ");

                for(int k=0;k<exce.length;++k){

                    System.out.print(exce[k].getName()+" ");

                    if(k<exce.length-1){

                        System.out.print(",");

                    }

                }

            }else{

                System.out.print(")");

            }

            System.out.println();

        }

    }

}

【运行结果】:

public java.lang.String  getSex ()

public void  setSex (java.lang.String arg0)

public void  sayChina ()

public void  sayHello (java.lang.String arg0,int arg1)

public final native void  wait (long arg0) throws java.lang.InterruptedException

public final void  wait () throws java.lang.InterruptedException

public final void  wait (long arg0,int arg1) throws java.lang.InterruptedException

public boolean  equals (java.lang.Object arg0)

public java.lang.String  toString ()

public native int  hashCode ()

public final native java.lang.Class  getClass ()

public final native void  notify ()

public final native void  notifyAll ()

【案例】接下来让我们取得其他类的全部属性吧,最后我讲这些整理在一起,也就是通过class取得一个类的全部框架

class hello {

    public static void main(String[] args) {

        Class<?> demo = null;

        try {

            demo = Class.forName("Reflect.Person");

        } catch (Exception e) {

            e.printStackTrace();

        }

        System.out.println("===============本类属性========================");

        // 取得本类的全部属性

        Field[] field = demo.getDeclaredFields();

        for (int i = 0; i < field.length; i++) {

            // 权限修饰符

            int mo = field[i].getModifiers();

            String priv = Modifier.toString(mo);

            // 属性类型

            Class<?> type = field[i].getType();

            System.out.println(priv + " " + type.getName() + " "

                    + field[i].getName() + ";");

        }

        System.out.println("===============实现的接口或者父类的属性========================");

        // 取得实现的接口或者父类的属性

        Field[] filed1 = demo.getFields();

        for (int j = 0; j < filed1.length; j++) {

            // 权限修饰符

            int mo = filed1[j].getModifiers();

            String priv = Modifier.toString(mo);

            // 属性类型

            Class<?> type = filed1[j].getType();

            System.out.println(priv + " " + type.getName() + " "

                    + filed1[j].getName() + ";");

        }

    }

}

【运行结果】:

===============本类属性========================

private java.lang.String sex;

===============实现的接口或者父类的属性========================

public static final java.lang.String name;

public static final int age;

【案例】其实还可以通过反射调用其他类中的方法:

class hello {

    public static void main(String[] args) {

        Class<?> demo = null;

        try {

            demo = Class.forName("Reflect.Person");

        } catch (Exception e) {

            e.printStackTrace();

        }

        try{

            //调用Person类中的sayChina方法

            Method method=demo.getMethod("sayChina");

            method.invoke(demo.newInstance());

            //调用Person的sayHello方法

            method=demo.getMethod("sayHello", String.class,int.class);

            method.invoke(demo.newInstance(),"Rollen",20);

             

        }catch (Exception e) {

            e.printStackTrace();

        }

    }

}

【运行结果】:

hello ,china

Rollen  20

【案例】调用其他类的set和get方法

class hello {

    public static void main(String[] args) {

        Class<?> demo = null;

        Object obj=null;

        try {

            demo = Class.forName("Reflect.Person");

        } catch (Exception e) {

            e.printStackTrace();

        }

        try{

         obj=demo.newInstance();

        }catch (Exception e) {

            e.printStackTrace();

        }

        setter(obj,"Sex","男",String.class);

        getter(obj,"Sex");

    }

 

    /**

     * @param obj

     *            操作的对象

     * @param att

     *            操作的属性

     * */

    public static void getter(Object obj, String att) {

        try {

            Method method = obj.getClass().getMethod("get" + att);

            System.out.println(method.invoke(obj));

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

 

    /**

     * @param obj

     *            操作的对象

     * @param att

     *            操作的属性

     * @param value

     *            设置的值

     * @param type

     *            参数的属性

     * */

    public static void setter(Object obj, String att, Object value,

            Class<?> type) {

        try {

            Method method = obj.getClass().getMethod("set" + att, type);

            method.invoke(obj, value);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}// end class

【运行结果】:

【案例】通过反射操作属性

class hello {

    public static void main(String[] args) throws Exception {

        Class<?> demo = null;

        Object obj = null;

 

        demo = Class.forName("Reflect.Person");

        obj = demo.newInstance();

 

        Field field = demo.getDeclaredField("sex");

        field.setAccessible(true);

        field.set(obj, "男");

        System.out.println(field.get(obj));

    }

}// end class

【案例】通过反射取得并修改数组的信息:

import java.lang.reflect.*;

class hello{

    public static void main(String[] args) {

        int[] temp={1,2,3,4,5};

        Class<?>demo=temp.getClass().getComponentType();

        System.out.println("数组类型: "+demo.getName());

        System.out.println("数组长度  "+Array.getLength(temp));

        System.out.println("数组的第一个元素: "+Array.get(temp, 0));

        Array.set(temp, 0, 100);

        System.out.println("修改之后数组第一个元素为: "+Array.get(temp, 0));

    }

}

【运行结果】:

数组类型:int

数组长度  5

数组的第一个元素:1

修改之后数组第一个元素为: 100

【案例】通过反射修改数组大小

class hello{

    public static void main(String[] args) {

        int[] temp={1,2,3,4,5,6,7,8,9};

        int[] newTemp=(int[])arrayInc(temp,15);

        print(newTemp);

        System.out.println("=====================");

        String[] atr={"a","b","c"};

        String[] str1=(String[])arrayInc(atr,8);

        print(str1);

    }

     

    /**

     * 修改数组大小

     * */

    public static Object arrayInc(Object obj,int len){

        Class<?>arr=obj.getClass().getComponentType();

        Object newArr=Array.newInstance(arr, len);

        int co=Array.getLength(obj);

        System.arraycopy(obj, 0, newArr, 0, co);

        return newArr;

    }

    /**

     * 打印

     * */

    public static void print(Object obj){

        Class<?>c=obj.getClass();

        if(!c.isArray()){

            return;

        }

        System.out.println("数组长度为: "+Array.getLength(obj));

        for (int i = 0; i < Array.getLength(obj); i++) {

            System.out.print(Array.get(obj, i)+" ");

        }

    }

}

【运行结果】:

数组长度为:15

1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 =====================

数组长度为:8

a b c null null null null null

动态代理

【案例】首先来看看如何获得类加载器:

class test{

     

}

class hello{

    public static void main(String[] args) {

        test t=new test();

        System.out.println("类加载器  "+t.getClass().getClassLoader().getClass().getName());

    }

}

【程序输出】:

类加载器  sun.misc.Launcher$AppClassLoader

其实在java中有三种类类加载器。

1)Bootstrap ClassLoader 此加载器采用c++编写,一般开发中很少见。

2)Extension ClassLoader 用来进行扩展类的加载,一般对应的是jrelibext目录中的类

3)AppClassLoader加载classpath指定的类,是最常用的加载器。同时也是java中默认的加载器。

如果想要完成动态代理,首先需要定义一个InvocationHandler接口的子类,已完成代理的具体操作。

package Reflect;

import java.lang.reflect.*;

 

//定义项目接口

interface Subject {

    public String say(String name, int age);

}

 

// 定义真实项目

class RealSubject implements Subject {

    @Override

    public String say(String name, int age) {

        return name + "  " + age;

    }

}

 

class MyInvocationHandler implements InvocationHandler {

    private Object obj = null;

 

    public Object bind(Object obj) {

        this.obj = obj;

        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj

                .getClass().getInterfaces(), this);

    }

 

    @Override

    public Object invoke(Object proxy, Method method, Object[] args)

            throws Throwable {

        Object temp = method.invoke(this.obj, args);

        return temp;

    }

}

 

class hello {

    public static void main(String[] args) {

        MyInvocationHandler demo = new MyInvocationHandler();

        Subject sub = (Subject) demo.bind(new RealSubject());

        String info = sub.say("Rollen", 20);

        System.out.println(info);

    }

}

【运行结果】:

Rollen  20

类的生命周期

在一个类编译完成之后,下一步就需要开始使用类,如果要使用一个类,肯定离不开JVM。在程序执行中JVM通过装载,链接,初始化这3个步骤完成。

类的装载是通过类加载器完成的,加载器将.class文件的二进制文件装入JVM的方法区,并且在堆区创建描述这个类的java.lang.Class对象。用来封装数据。但是同一个类只会被类装载器装载以前

链接就是把二进制数据组装为可以运行的状态。

 

链接分为校验,准备,解析这3个阶段

校验一般用来确认此二进制文件是否适合当前的JVM(版本),

准备就是为静态成员分配内存空间,。并设置默认值

解析指的是转换常量池中的代码作为直接引用的过程,直到所有的符号引用都可以被运行程序使用(建立完整的对应关系)

完成之后,类型也就完成了初始化,初始化之后类的对象就可以正常使用了,直到一个对象不再使用之后,将被垃圾回收。释放空间。

当没有任何引用指向Class对象时就会被卸载,结束类的生命周期

将反射用于工厂模式

先来看看,如果不用反射的时候,的工厂模式吧:

/**

 * @author Rollen-Holt 设计模式之 工厂模式

 */

 

interface fruit{

    public abstract void eat();

}

 

class Apple implements fruit{

    public void eat(){

        System.out.println("Apple");

    }

}

 

class Orange implements fruit{

    public void eat(){

        System.out.println("Orange");

    }

}

 

// 构造工厂类

// 也就是说以后如果我们在添加其他的实例的时候只需要修改工厂类就行了

class Factory{

    public static fruit getInstance(String fruitName){

        fruit f=null;

        if("Apple".equals(fruitName)){

            f=new Apple();

        }

        if("Orange".equals(fruitName)){

            f=new Orange();

        }

        return f;

    }

}

class hello{

    public static void main(String[] a){

        fruit f=Factory.getInstance("Orange");

        f.eat();

    }

 

}

这样,当我们在添加一个子类的时候,就需要修改工厂类了。如果我们添加太多的子类的时候,改的就会很多。

现在我们看看利用反射机制:

package Reflect;

 

interface fruit{

    public abstract void eat();

}

 

class Apple implements fruit{

    public void eat(){

        System.out.println("Apple");

    }

}

 

class Orange implements fruit{

    public void eat(){

        System.out.println("Orange");

    }

}

 

class Factory{

    public static fruit getInstance(String ClassName){

        fruit f=null;

        try{

            f=(fruit)Class.forName(ClassName).newInstance();

        }catch (Exception e) {

            e.printStackTrace();

        }

        return f;

    }

}

class hello{

    public static void main(String[] a){

        fruit f=Factory.getInstance("Reflect.Apple");

        if(f!=null){

            f.eat();

        }

    }

}

现在就算我们添加任意多个子类的时候,工厂类就不需要修改。

上面的爱吗虽然可以通过反射取得接口的实例,但是需要传入完整的包和类名。而且用户也无法知道一个接口有多少个可以使用的子类,所以我们通过属性文件的形式配置所需要的子类。

下面我们来看看: 结合属性文件的工厂模式

首先创建一个fruit.properties的资源文件,

内容为:

apple=Reflect.Apple

orange=Reflect.Orange

然后编写主类代码:

package Reflect;

 

import java.io.*;

import java.util.*;

 

interface fruit{

    public abstract void eat();

}

 

class Apple implements fruit{

    public void eat(){

        System.out.println("Apple");

    }

}

 

class Orange implements fruit{

    public void eat(){

        System.out.println("Orange");

    }

}

 

//操作属性文件类

class init{

    public static Properties getPro() throws FileNotFoundException, IOException{

        Properties pro=new Properties();

        File f=new File("fruit.properties");

        if(f.exists()){

            pro.load(new FileInputStream(f));

        }else{

            pro.setProperty("apple", "Reflect.Apple");

            pro.setProperty("orange", "Reflect.Orange");

            pro.store(new FileOutputStream(f), "FRUIT CLASS");

        }

        return pro;

    }

}

 

class Factory{

    public static fruit getInstance(String ClassName){

        fruit f=null;

        try{

            f=(fruit)Class.forName(ClassName).newInstance();

        }catch (Exception e) {

            e.printStackTrace();

        }

        return f;

    }

}

class hello{

    public static void main(String[] a) throws FileNotFoundException, IOException{

        Properties pro=init.getPro();

        fruit f=Factory.getInstance(pro.getProperty("apple"));

        if(f!=null){

            f.eat();

        }

    }

}

【运行结果】:Apple

 Java反射机制

一、什么是反射机制             简单的来说,反射机制指的是程序在运行时能够获取自身的信息。在java中,只要给定类的名字,        那么就可以通过反射机制来获得类的所有信息。    二、哪里用到反射机制     有些时候,我们用过一些知识,但是并不知道它的专业术语是什么,在刚刚学jdbc时用过一行代码,     Class.forName("com.mysql.jdbc.Driver.class").newInstance();但是那时候只知道那行代码是生成        驱动对象实例,并不知道它的具体含义。听了反射机制这节课后,才知道,原来这就是反射,现在很多开        框架都用到反射机制,hibernate、struts都是用反射机制实现的。    三、反射机制的优点与缺点             为什么要用反射机制?直接创建对象不就可以了吗,这就涉及到了动态与静态的概念,        静态编译:在编译时确定类型,绑定对象,即通过。        动态编译:运行时确定类型,绑定对象。动态编译最大限度发挥了java的灵活性,体现了多        态的应用,有以降低类之间的藕合性。        一句话,反射机制的优点就是可以实现动态创建对象和编译,体现出很大的灵活性,特别是在J2EE的开发中        它的灵活性就表现的十分明显。比如,一个大型的软件,不可能一次就把把它设计的很完美,当这个程序编        译后,发布了,当发现需要更新某些功能时,我们不可能要用户把以前的卸载,再重新安装新的版本,假如        这样的话,这个软件肯定是没有多少人用的。采用静态的话,需要把整个程序重新编译一次才可以实现功能        的更新,而采用反射机制的话,它就可以不用卸载,只需要在运行时才动态的创建和编译,就可以实现该功        能。           它的缺点是对性能有影响。使用反射基本上是一种解释操作,我们可以告诉JVM,我们希望做什么并且它        满足我们的要求。这类操作总是慢于只直接执行相同的操作。    四、利用反射机制能获得什么信息              一句话,类中有什么信息,它就可以获得什么信息,不过前提是得知道类的名字,要不就没有后文了        首先得根据传入的类的全名来创建Class对象。        Class c=Class.forName("className");注明:className必须为全名,也就是得包含包名,比如,cn.netjava.pojo.UserInfo;        Object obj=c.newInstance();//创建对象的实例        OK,有了对象就什么都好办了,想要什么信息就有什么信息了。       获得构造函数的方法        Constructor getConstructor(Class[] params)//根据指定参数获得public构造器

    Constructor[] getConstructors()//获得public的所有构造器

    Constructor getDeclaredConstructor(Class[] params)//根据指定参数获得public和非public的构造器

    Constructor[] getDeclaredConstructors()//获得public的所有构造器       获得类方法的方法        Method getMethod(String name, Class[] params),根据方法名,参数类型获得方法

    Method[] getMethods()//获得所有的public方法

    Method getDeclaredMethod(String name, Class[] params)//根据方法名和参数类型,获得public和非public的方法

    Method[] getDeclaredMethods()//获得所以的public和非public方法       获得类中属性的方法        Field getField(String name)//根据变量名得到相应的public变量

    Field[] getFields()//获得类中所以public的方法

    Field getDeclaredField(String name)//根据方法名获得public和非public变量

    Field[] getDeclaredFields()//获得类中所有的public和非public方法       常用的就这些,知道这些,其他的都好办……    五、用反射机制能干什么事             刚开始在使用jdbc时侯,在编写访问数据库时写到想吐,有八个表,每个表都有增删改查中操作        那时候还不知道有反射机制这个概念,所以就对不同的表创建不同的dao类,这样不仅开发速率地,而且代码        冗余的厉害,最要命的是看着差不多的,然后直接复制修改,由于容易犯各种低级的错误(大小写啊,多一        个或少一个字母啊……),一个错误就可以让你找半天。            有了java反射机制,什么都好办了,只需要写一个dao类,四个方法,增删改查,传入不同的对象,就OK啦,        无需为每一个表都创建dao类,反射机制会自动帮我们完成剩下的事情,这就是它的好处。说白了,反射机制就是专门        帮我们做那些重复的有规则的事情,所以现在很多的自动生成代码的软件就是运用反射机制来完成的,只要你按照规则        输入相关的参数,所以低级的程序员慢慢的就被抹杀了,为什么?因为代码都不用写了,随便一个人都会开发,还要程        序员干什么啊?所以我们只有一条出路,那就是努力努力再努力,成为高级程序员,专门开发傻瓜软件,让其他程序员  到 一边凉快去,呵呵~    六、用反射机制实现对数据库数据的增、查例子         基本原理;保存数据时,把需要保存的对象的属性值全部取出来再拼凑sql语句                     查询时,将查询到的数据全部包装成一个java对象。        游戏规则:俗话说的好,无规矩不成方圆,特别是程序来说,它只能做有规则的事情,没有规则的它干不了,好,那就                  先定规则                  1)数据库的每一个表对象一个pojo类,表中的每一个字段对应pojo类的中的一个属性。                     并且pojo类的名字和表的名字相同,属性名和字段名相同,大小写没有关系,因为数据库一般不区分大小写                2)为pojo类中的每一个属性添加标准的set和get方法。        有了游戏规则,那么开始游戏吧。

1、首先数据库的有一个表,假设数据库名称为:blogsystem,里面的一个表名userinfo。如图:

2、创建对应的pojo类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package cn.netjava.pojo;
 
public class UserInfo {
private int id;
private String name;
private String pwd;
private int age;
 
@Override
public String toString() {
    return "UserInfo [id=" + id + ", name=" + name + ", pwd=" + pwd + ", age="
            + age + "]";
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getPwd() {
    return pwd;
}
public void setPwd(String pwd) {
    this.pwd = pwd;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
 
}
2、编写获得数据库连接的工厂类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package cn.netjava.factory;
 
import java.sql.Connection;
import java.sql.DriverManager;
 
public class Connect2DBFactory {
    public static Connection getDBConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/blogsystem";
            String user = "root";
            String password = "netjava";
            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return conn;
    }
}

3、好戏开始啦,编写操作数据库的dao类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package cn.netjava.session;
 
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
 
import cn.netjava.factory.Connect2DBFactory;
import cn.netjava.pojo.UserInfo;
 
public class NetJavaSession {
    /**
     * 解析出保存对象的sql语句
     *
     * @param object
     *            :需要保存的对象
     * @return:保存对象的sql语句
     */
    public static String getSaveObjectSql(Object object) {
        // 定义一个sql字符串
        String sql = "insert into ";
        // 得到对象的类
        Class c = object.getClass();
        // 得到对象中所有的方法
        Method[] methods = c.getMethods();
        // 得到对象中所有的属性
        Field[] fields = c.getFields();
        // 得到对象类的名字
        String cName = c.getName();
        // 从类的名字中解析出表名
        String tableName = cName.substring(cName.lastIndexOf(".") + 1,
                cName.length());
        sql += tableName + "(";
        List<String> mList = new ArrayList<String>();
        List vList = new ArrayList();
        for (Method method : methods) {
            String mName = method.getName();
            if (mName.startsWith("get") && !mName.startsWith("getClass")) {
                String fieldName = mName.substring(3, mName.length());
                mList.add(fieldName);
                System.out.println("字段名字----->" + fieldName);
                try {
                    Object value = method.invoke(object, null);
                    System.out.println("执行方法返回的值:" + value);
                    if (value instanceof String) {
                        vList.add(""" + value + """);
                        System.out.println("字段值------>" + value);
                    } else {
                        vList.add(value);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        for (int i = 0; i < mList.size(); i++) {
            if (i < mList.size() - 1) {
                sql += mList.get(i) + ",";
            } else {
                sql += mList.get(i) + ") values(";
            }
        }
        for (int i = 0; i < vList.size(); i++) {
            if (i < vList.size() - 1) {
                sql += vList.get(i) + ",";
            } else {
                sql += vList.get(i) + ")";
            }
        }
 
        return sql;
    }
 
    public static List getDatasFromDB(String tableName, int Id) {
 
        return null;
 
    }
 
    /**
     * 将对象保存到数据库中
     *
     * @param object
     *            :需要保存的对象
     * @return:方法执行的结果;1:表示成功,0:表示失败
     */
    public int saveObject(Object object) {
        Connection con = Connect2DBFactory.getDBConnection();
        String sql = getSaveObjectSql(object);
        try {
            // Statement statement=(Statement) con.createStatement();
            PreparedStatement psmt = con.prepareStatement(sql);
            psmt.executeUpdate();
            return 1;
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }
 
    /**
     * 从数据库中取得对象
     *
     * @param arg0
     *            :对象所属的类
     * @param id
     *            :对象的id
     * @return:需要查找的对象
     */
    public Object getObject(String className, int Id) {
        // 得到表名字
        String tableName = className.substring(className.lastIndexOf(".") + 1,
                className.length());
        // 根据类名来创建Class对象
        Class c = null;
        try {
            c = Class.forName(className);
 
        } catch (ClassNotFoundException e1) {
 
            e1.printStackTrace();
        }
        // 拼凑查询sql语句
        String sql = "select * from " + tableName + " where Id=" + Id;
        System.out.println("查找sql语句:" + sql);
        // 获得数据库链接
        Connection con = Connect2DBFactory.getDBConnection();
        // 创建类的实例
        Object obj = null;
        try {
 
            Statement stm = con.createStatement();
            // 得到执行查寻语句返回的结果集
            ResultSet set = stm.executeQuery(sql);
            // 得到对象的方法数组
            Method[] methods = c.getMethods();
            // 遍历结果集
            while (set.next()) {
                obj = c.newInstance();
                // 遍历对象的方法
                for (Method method : methods) {
                    String methodName = method.getName();
                    // 如果对象的方法以set开头
                    if (methodName.startsWith("set")) {
                        // 根据方法名字得到数据表格中字段的名字
                        String columnName = methodName.substring(3,
                                methodName.length());
                        // 得到方法的参数类型
                        Class[] parmts = method.getParameterTypes();
                        if (parmts[0] == String.class) {
                            // 如果参数为String类型,则从结果集中按照列名取得对应的值,并且执行改set方法
                            method.invoke(obj, set.getString(columnName));
                        }
                        if (parmts[0] == int.class) {
                            method.invoke(obj, set.getInt(columnName));
                        }
                    }
 
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }
}

4、开始测试效果怎么样:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package cn.netjava.tester;
 
import cn.netjava.pojo.UserInfo;
import cn.netjava.session.NetJavaSession;
 
public class Tester {
    public static void main(String args[]) {
        //获得NetJavaSession对象
        NetJavaSession session = new NetJavaSession();
        //创建一个UserInfo对象
        UserInfo user = new UserInfo();
        //设置对象的属性
        user.setId(6988);
        user.setAge(44);
        user.setPwd("pwd");
        user.setName("champion");
        //将对象保存到数据库中
        String sql = session.getSaveObjectSql(user);
        System.out.println("保存对象的sql语句:" + sql);
        //查找对象
        UserInfo userInfo = (UserInfo) session.getObject(
                "cn.netjava.pojo.UserInfo", 6988);
        System.out.println("获取到的信息:" + userInfo);
 
    }
}

5、打印出来的结果:

七、总节一下

      总的来说,java反射机制是一个很好用的东西,用它可以解决很多死的东西,因为反射机制的灵活行很大,有了他,我们就不要花太多的时间来写操做数据库的代码了,而是方法更多的时间在项目的逻辑功能上,这个可以很大的减少开发时间,而且代码的可读性好。先在的很多开源框架都是才用的反射机制,它只要配置文件,然后按规则来调用他的方法就可以了。

原文地址:https://www.cnblogs.com/WuXuanKun/p/5549873.html