java 基础之 反射技术

1. java代码

在 java 语言中最核心的就是代码的运行, 按照面向对象的思想,在调用java代码时往往需要先创建对象,再调用方法, 而写在方法中的即所谓的java 代码

 

一段java代码在程序运行期间会经历三个阶段: source-->class-->runtime

 

2. Class 对象

         在java中用一个Class对象来表示一个java类的class阶段

         Class对象封装了一个java类中定义的成员变量、成员方法、构造方法、类名、包名等

获得class对象的三种方式和区别

// 1. 根据给定的类名来获得  用于类加载

String classname ="cn.itcast.reflect.Person";       //来自配置文件

Class clazz = Class.forName(classname);       // 此对象代表Person.class

 

// 2. 如果拿到了对象,不知道是什么类型   用于获得对象的类型

Object obj = new Person();

Class clazz1 = obj.getClass();  // 获得对象具体的类型

 

// 3. 如果是明确地获得某个类的Class对象  主要用于传参

Class clazz2 = Person.class;   

// 在java中所有的类型都会对应一个Class对象 int Integer

Class intClazz = int.class;

Class intarrClazz = int[].class;

Class voidClazz = void.class;

 

3. 反射的概念

反射就是获得一个java类的各个组成部分

// 反射类的成员方法

Class clazz = Person.class;

Method method =clazz.getMethod(methodName, new Class[]{paramClazz1, paramClazz2});

method.invoke();

        

// 反射类的构造函数

Constructor con =clazz.getConstructor(new Class[]{paramClazz1, paramClazz2,...})

con.newInstance(params...)

 

// 反射类的属性

Field field =clazz.getField(fieldName);

field.setAccessible(true);

field.setObject(value);

4. 反射用在哪里

         到底框架是什么?  框架就是将开发中大量重复的代码集中起来写个通用的程序

         框架就是用反射来实现的

         框架需要现在的类调用将来写的类

         框架是将来的程序员调用的,框架不能实现完整的功能,框架只是一些一些通用的代码

         框架要运行一定会依赖将来写的类

         现在写的类要调用将来写的类,我们先针对接口进行调用,将来的类需要实现接口,那么方法就固定了

         但是将来写的类的类名我们无法获知,这时就需要调用者通过配置文件告诉框架具体的类名

Person.java

// 1. 根据给定的类名来获得  用于类加载

package xgp_reflect;

 

import java.awt.List;

import java.io.InputStream;

 

public class Person {

 

         publicString name= "aaaa";

         privatestatic int password=123;

         //1、类构造函数

         publicPerson(){

                   System.out.println("无参数构造函数!");

         }

        

         publicPerson(String name){

                   System.out.println(name);

         }

        

         publicPerson(String name, int password){

                   System.out.println(name+password);

         }

        

         privatePerson(List list){

                   System.out.println("list");

         }

        

         //2、方法

         publicvoid aa1(){

                   System.out.println("aa1无参数方法");

         }

        

         publicvoid aa1(String name, int password){

                   System.out.println(name+":"+password+"两个参数的方法");

         }

        

         publicvoid aa1(InputStream in){

                   System.out.println(in);

         }

        

         publicClass[] aa1(String name, int[] password){

                   returnnew Class[]{String.class} ;

         }

        

         privatestatic void aa1(int num){

                   System.out.println(num+"静态方法");

         }

        

         public  static void main(String[] args){

                   System.out.println("main");

         }

}

Demo01.java

package xgp_reflect;

 

public class Demo01 {

/**

 *

 * 反射,加载类,获得类的字节码

 * @throws ClassNotFoundException

 */

         publicstatic void main(String[] args) throws ClassNotFoundException {

                   //方法1

                   Classclazz = Class.forName("/stringjava/src/xgp_reflect/Person.java");

                  

                   //方法2

                   Classclazz2 = new Person().getClass();

                  

                   //方法3

                   Classclazz3 = Person.class;

         }

 

}

 

Demo02.java

// package xgp_reflect;

 

import java.awt.List;

importjava.lang.reflect.Constructor;

importjava.lang.reflect.InvocationTargetException;

import java.util.ArrayList;

 

import org.junit.Test;

 

public class Demo02 {

         /**

          * 反射类的构造函数,创建类的对象

 

          */

         @Test

         //反射构造函数publicPerson()

         publicvoid test1() throws Exception{

                   Classclazz = Class.forName("xgp_reflect.Person");

                   Constructorc = clazz.getConstructor(null);

                   Personp = (Person) c.newInstance(null);

                  

                   System.out.println(p.name);

         }

        

         //反射构造函数publicPerson(String name)

         @Test

         publicvoid test2() throws Exception{

                   Classclazz = Class.forName("xgp_reflect.Person");

                   Constructorc = clazz.getConstructor(String.class);

                   Personp = (Person) c.newInstance("xxxx");

                  

                   System.out.println(p.name);

         }

        

         //反射构造函数publicPerson(String name, int password)

                   @Test

                   publicvoid test3() throws Exception{

                            Classclazz = Class.forName("xgp_reflect.Person");

                            Constructorc = clazz.getConstructor(String.class, int.class);

                            Personp = (Person) c.newInstance("xiaoguoping",25);

                           

                            System.out.println(p.name);

                   }

                  

         //反射构造函数publicPerson(List list)

         @Test

         publicvoid test4() throws Exception{

                   Classclazz = Class.forName("xgp_reflect.Person");

                   Constructorc = clazz.getDeclaredConstructor(List.class);

                   c.setAccessible(true);

                   Personp = (Person) c.newInstance(new List());

                  

                   System.out.println(p.name);

         }

        

         //无参数构造函数的另一种方法

                   @Test

                   publicvoid test5() throws Exception{

                            Classclazz = Class.forName("xgp_reflect.Person");

                            Personp = (Person) clazz.newInstance();

                           

                            System.out.println(p.name);

                   }

 }

 

Demo03.java

// package xgp_reflect;

import java.io.FileInputStream;

import java.io.InputStream;

import java.lang.reflect.Method;

 

import org.junit.Test;

 

public class Demo3 {

         /**

          * 反射类的方法

          */

         @Test

         //反射类的方法--publicvoid aa1()

         publicvoid test1() throws Exception{

                   Personp = new Person();

                   Classclazz = Class.forName("xgp_reflect.Person");

                   Methodmethod = clazz.getMethod("aa1", null);

                   method.invoke(p,null);

                   }

         @Test

         //反射类的方法--publicvoid aa1(String name, int password)

         publicvoid test2() throws Exception{

                   Personp = new Person();

                   Classclazz = Class.forName("xgp_reflect.Person");

                   Methodmethod= clazz.getMethod("aa1", String.class,int.class);

                   method.invoke(p,"xiaoguoping",25);

         }

        

         @Test

         //反射类的方法--publicClass[] aa1(String name, int[] password)

         publicvoid test3() throws Exception{

                   Personp = new Person();

                   Classclazz = Class.forName("xgp_reflect.Person");

                   Methodmethod= clazz.getMethod("aa1", String.class,int[].class);

                   Classcs[] = (Class[]) method.invoke(p, "xiaoguoping", new int[]{1,2});

                   System.out.println(cs[0]);

         }

        

         @Test

         //反射类的方法--publicvoid aa1(InputStream in)

         publicvoid test4() throws Exception{

                   Personp = new Person();

                   Classclazz = Class.forName("xgp_reflect.Person");

                   Methodmethod= clazz.getMethod("aa1",InputStream.class);

                   method.invoke(p,newFileInputStream("C:\\unknow.log"));

         }

                  

         @Test

         //反射类的方法--privatestatic void aa1(int num)

         publicvoid test5() throws Exception{

                   //Personp = new Person();静态方法可以不传对象

                   Classclazz = Class.forName("xgp_reflect.Person");

                   Methodmethod= clazz.getDeclaredMethod("aa1",int.class);

                   method.setAccessible(true);

                   method.invoke(null,23);

         }

         @Test

         //反射类的方法--publicstatic void main(String[] args)

         publicvoid test6() throws Exception{

                   Classclazz = Class.forName("xgp_reflect.Person");

                   Methodmethod= clazz.getMethod("main",String[].class);

                   //method.invoke(null,newString[]{"aa","bb"});//JDK1.4 main(string s1,string s2)拆开参数赋值

                   //method.invoke(null,(Object)new String[]{"aa","bb"});

                   method.invoke(null,new Object[]{new String[]{"aa","bb"}});

         }

}

 

Demo04.java

// package xgp_reflect;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

 

import org.junit.Test;

 

public class Demo04 {

         /**

          * 反射类的字段--属性,封装数据

          */

         @Test

         //反射类的字段--publicString name= "aaaa";

         publicvoid test1() throws Exception{

                   Personp = new Person();

                   Classclazz = Class.forName("xgp_reflect.Person");

                   Fieldfield = clazz.getField("name");

                   //获取字段的值

                   Objectvalue= field.get(p);

                   //获取字段的类型

                   Classtype = field.getType();

                   if(type.equals(String.class)) {

                            Stringsvalue = (String) value;

                            System.out.println(svalue);//aaaa

                   }

                   //设置字段的值

                   field.set(p,"xxxx");

                   System.out.println(p.name);//xxxx

         }

        

         @Test

         //反射类的字段--privatestatic int password=123;

         publicvoid test2() throws Exception{

                   Personp = new Person();

                   Classclazz = Class.forName("xgp_reflect.Person");

                   Fieldfield = clazz.getDeclaredField("password");

                   field.setAccessible(true);

                   Objectvalue = field.get(p);

                   System.out.println(value);

         }

}

版权声明:本文为小平果原创文章,转载请注明:http://blog.csdn.net/i10630226

posted @ 2015-07-25 20:36  dingxiaoyue  阅读(138)  评论(0编辑  收藏  举报