Java之反射的应用

时间:2023-01-17 23:35:56

 

package com.zheges;

import java.util.Date;

public class Customer {//JavaBean 对象
private String name;
private int password;
public String present = "God";
private Date date; @Override
public String toString() {
return "Customer [name=" + name + ", password=" + password
+ ", present=" + present + ", date=" + date + "]";
} public String getPresent() {
return present;
}
public void setPresent(String present) {
this.present = present;
}
public String getName() {
return name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public void setName(String name) {
this.name = name;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getAB(){
return "AB";
}
}

 

package com.zheges;

import static org.junit.Assert.assertEquals;//静态导入Assert所有静态方法
import java.lang.reflect.Field;
import org.junit.Before;
import org.junit.Test; /**
* 项目名称:Reflection
* 类名称:FirDemo
* 类描述:反射的基本应用
* 创建人:ZHe
* 创建时间:2015年8月29日 下午5:01:43
* 修改人:ZHe
* 修改时间:2015年8月29日 下午5:01:43
*/
public class FirDemo { private Class<?> clazz;//类的字节码
private Customer customer = new Customer(); /**
* 1.加载类,并且获得类的字节码
* @throws ClassNotFoundException
*/
@Before
public void getClassLoader() throws ClassNotFoundException {
//1.使用Class的静态方法加载
clazz = Class.forName("com.zheges.Customer");//注意:这里要使用类的全名
//2.通过类对象获得其字节码
clazz = new Customer().getClass();
//3.通过类的静态属性获得
clazz = Customer.class; assertEquals("com.zheges.Customer",clazz.getName());
} /**
* 2.获得类的字段(注意:不等同于属性,属性由getter来确定!)
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
@Test
public void getClassProperties() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{ //1.获得私有字段及其类型
Field field = clazz.getDeclaredField("name");
Class<?> type = field.getType();
assertEquals(String.class, type); //2.获得公有字段及其类型
Field field1 = clazz.getField("present");
Class<?> type1 = field1.getType();
assertEquals(String.class, type1); //3.true if this object is the same as the obj argument; false otherwise.
assertEquals(true, field.equals(clazz.getDeclaredField("name"))); //4.设置某个对象上该字段的值
field.setAccessible(true);//该字段是私有的,需要设置setAccessible
field.set(customer,"ZheGes"); field1.set(customer, "Nor"); assertEquals(customer.getName(), "ZheGes");
assertEquals(customer.getPresent(), "Nor"); //5.获取某个对象上该字段的值
assertEquals(field.get(customer), "ZheGes");//前提是该私有变量设置了Accessible
assertEquals(field1.get(customer), "Nor");
}
}

 

package com.zheges;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import static org.junit.Assert.*; import org.junit.Ignore;
import org.junit.Test; /**
* 项目名称:Reflection
* 类名称:SecDemo
* 类描述:反射高级应用:内省
* 创建人:ZHe
* 创建时间:2015年8月29日 下午5:03:02
* 修改人:ZHe
* 修改时间:2015年8月29日 下午5:03:02
*/
public class SecDemo {
//内省:通过反射的方式访问javabean的技术
//JavaBean:1.必须有无参的构造函数 2.属性必须私有(属性数目由get数目来定,并非由字段来定!)3.提供标准的getter和setter //1.打印Customer的所有属性(包含Object的属性)
/*result:
AB-----Customer getter
class ----Object getter,getClass---->这个方法是继承Object的
date
name
password
present*/
@Ignore
public void getProperties() throws IntrospectionException{
BeanInfo beanInfo = Introspector.getBeanInfo(Customer.class);
PropertyDescriptor [] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
System.out.println(propertyDescriptor.getName());
}
} //2.打印Customer的所有属性(不包含Object的属性)
@Ignore
public void getOwnProperties() throws IntrospectionException{
BeanInfo beanInfo = Introspector.getBeanInfo(Customer.class,Object.class);
PropertyDescriptor [] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
System.out.println(propertyDescriptor.getName());
}
} //3.操作JavaBean的指定属性
@Test
public void actProperty() throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
Customer customer = new Customer(); PropertyDescriptor propertyDescriptor = new PropertyDescriptor("name", Customer.class);
Method method = propertyDescriptor.getWriteMethod();
method.invoke(customer, "zheGes"); Method method2 = propertyDescriptor.getReadMethod();
System.out.println(method2.invoke(customer, null));
} //4.获得当前操作属性的类型
@Ignore
public void getPropertyType() throws IntrospectionException{
PropertyDescriptor propertyDescriptor = new PropertyDescriptor("name", Customer.class);
assertEquals(String.class, propertyDescriptor.getPropertyType());
} }

 

package com.zheges;

import static org.junit.Assert.assertTrue;

import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import org.junit.Ignore;
import org.junit.Test; /**
* 项目名称:Reflection
* 类名称:ThrDemo
* 类描述:反射的高级应用2:BeanUtils
* 创建人:ZHe
* 创建时间:2015年8月29日 下午5:50:20
* 修改人:ZHe
* 修改时间:2015年8月29日 下午5:50:20
*/
public class ThrDemo {
private Customer customer = new Customer(); //1.BeanUtils操作属性
@Ignore
public void actProperty() throws IllegalAccessException, InvocationTargetException, Exception{ BeanUtils.setProperty(customer, "name", "ZHeGes");
BeanUtils.setProperty(customer, "password", "404");//发生了String转int,但这种转换只支持8种基础类型! System.out.println(BeanUtils.getProperty(customer, "name")+" "+
BeanUtils.getProperty(customer, "password"));
} //2.对于非基础类型的转换,则要给BeanUtils注册转换器
@Ignore
public void registConver() throws Exception { //注册一个日期转换器,Converter接口,使用匿名内部类实现
ConvertUtils.register(new Converter(){
@Override
public Object convert(Class type, Object value) {
if(null == value){
return null;
}
if( !(value instanceof String)){
throw new ConversionException("只支持String类型的转换");
}
String str = (String)value;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); try {
return simpleDateFormat.parse(str);
} catch (ParseException e) {
throw new RuntimeException(e);//异常链不能断!
}
} }, Date.class); BeanUtils.setProperty(customer, "date", "1992-3-18");
//The property's value, converted to a String
System.out.println(BeanUtils.getProperty(customer, "date"));
System.out.println(customer.getDate().toLocaleString());
} //3.使用Apach公司提供的日期转换器
@Ignore
public void registConver2() throws Exception{
ConvertUtils.register(new DateLocaleConverter(), Date.class);
BeanUtils.setProperty(customer, "date", "1992-3-18");
System.out.println(customer.getDate().toLocaleString());
} //4.使用BeanUtils将Map对象填充到JavaBean
@Ignore
public void usePopulate() throws Exception{
Map map = new HashMap<>();
map.put("name", "ZheGes");
map.put("password", "123");
map.put("date", "1992-2-1"); //日期转换器
ConvertUtils.register(new DateLocaleConverter(), Date.class); BeanUtils.populate(customer, map);
System.out.println(customer);
} @Test
public void test(){
String str = "hell";
String str1 = str;
str = "wofl";
System.out.println(str+" "+str1);
} @Ignore
public void test2(){
Class<String> t1 = String.class;
//Class<String> t2 = Date.class; false:加了类型约束,必须是类String的字节码,否则报错!
Class t3 = String.class;
assertTrue(t1 == t3);
}
}