java反射详解(java.lang.reflect)
1.常用基本方法使用
获取Class的三种方法
//第一种方式:
Classc1 = Class.forName("类路径");
//第二种方式:
//java中每个类型都有class 属性.
Classc2 = Employee.class;
//第三种方式:
//java语言中任何一个java对象都有getClass 方法
Employee e = new Employee();
Classc3 = e.getClass(); //c3是运行时类 (e的运行时类是Employee)
创建对象:获取类以后我们来创建它的对象,利用newInstance:
Class c =Class.forName("Employee");
//创建此Class 对象所表示的类的一个新实例
Object o = c.newInstance(); //调用了Employee的无参数构造方法.
通过Class类获取成员变量、成员方法、接口、超类、构造方法等
在java.lang.Object 类中定义了getClass()方法,因此对于任意一个Java对象,都可以通过此方法获得对象的类型。Class类是Reflection API 中的核心类,它有以下方法
getName():获得类的完整名字。
getFields():获得类的public类型的属性。
getDeclaredFields():获得类的所有属性。
getMethods():获得类的public类型的方法。
getDeclaredMethods():获得类的所有方法。
getMethod(String name, Class[] parameterTypes):获得类的特定方法,name参数指定方法的名字,parameterTypes 参数指定方法的参数类型。
getConstructors():获得类的public类型的构造方法。
getConstructor(Class[] parameterTypes):获得类的特定构造方法,parameterTypes 参数指定构造方法的参数类型。
newInstance():通过类的不带参数的构造方法创建这个类的一个对象。
成员变量为private,故必须操作:Field.setAccessible(true); 获取访问权限
2.反射事列
通过反射动态给属性赋值
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
*
* @auther SHDY
*
*/
public class Test {
/**
*
* @designer li.yiyong 2015-2-11
* @developer li.yiyong 2015-2-11
* @modified by
* @param args void
*/
public static void main(String[] args) {
File file = new File("C:\\Users\\SHDY\\Desktop\\test.txt");
String id = "id";
String name = "name";
String age = "age";
List<String> list1 = new ArrayList<String>();
list1.add(id);
list1.add(name);
list1.add(age);
List<String> list2 = new ArrayList<String>();
list2.add(id);
list2.add(age);
list2.add(name);
List<String> list3 = new ArrayList<String>();
list3.add(name);
list3.add(id);
list3.add(age);
List<String> list4 = new ArrayList<String>();
list4.add(id);
list4.add(age);
list4.add(name);
List<List<String>> list = new ArrayList<List<String>>();
list.add(list1);
list.add(list2);
list.add(list3);
list.add(list4);
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,"gbk");
BufferedReader reader = new BufferedReader(isr);
int num = 0;
String str = null;
Student student = null;
while((str = reader.readLine()) != null){
List<String> params = list.get(num);
String[] arr = str.split("\\|");
student = new Student();
for(int i = 0 ;i < params.size();i++){
String attributeName = params.get(i);
Field field = student.getClass().getDeclaredField(attributeName);
String type = field.getGenericType().toString();
//根据属性类型赋值
if(type.equals("class java.lang.String")){
field.set(student, arr[i]);
}else if(type.equals("class java.lang.Integer")){
field.set(student, Integer.parseInt(arr[i]));
}else if(type.equals("class java.lang.Long")){
field.set(student, Long.parseLong(arr[i]));
}
}
num++;
System.out.println(student);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static class Student{
public Long id;
public String name;
public Integer age;
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public Integer getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(Integer age) {
this.age = age;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age
+ "]";
}
}
}
test.txt 配置文件内容:
1|小米|12
2|12|李是
刘校长|3|46
4|23|李老师
通过反射动态调用方法
package ref;
import java.lang.reflect.Method;
public class Methoder {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO 自动生成方法存根
Class c = Class.forName("ref.Test");
// Class ptypes[] ={Class.forName("java.lang.String")};
Class types[] =new Class[1];
types[0]=Class.forName("java.lang.String");//方法的参数对应下面的String aa
Method m = c.getMethod("sayHello",types );//动态调用sayHello方法
Test t = new Test();
m.invoke(t,"hellojava" );//传给方法的的参数
}
}
package ref;
class Test{
public void sayHello(String aa){
System.out.println("Test:"+aa);
}
}
3.反射的应用
1.反射是java的一大亮点,对我们应用程序的开发有着举足轻重的作用,如框架的应用:spring动态代理、Aop、struts绑定赋值、数据库的动态切换、注解的使用...
2.在开发多个相似的功能时,我们可以运用面向对象使用,将多态、反射、配置文件结合起来,尽量做到通过修改配置文件,就可以增加新的功能,提高代码的扩展性。