Java之反射的应用
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);
}
}
Java之反射的应用的更多相关文章
- JAVA的反射理解
1----------------------------反射的概念----------------------------------------------- JAVA的反射机制是在运行状态中,对 ...
- java的反射
JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意方法和属性:这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制. ...
- iOS运行时编程(Runtime Programming)和Java的反射机制对比
运行时进行编程,类似Java的反射.运行时编程和Java反射的对比如下: 1.相同点 都可以实现的功能:获取类信息.属性设置获取.类的动态加载(NSClassFromString(@“clas ...
- Java 类反射机制分析
Java 类反射机制分析 一.反射的概念及在Java中的类反射 反射主要是指程序可以访问.检测和修改它本身状态或行为的一种能力.在计算机科学领域,反射是一类应用,它们能够自描述和自控制.这类应用通过某 ...
- java的反射机制
一.java的反射机制浅谈 最近研究java研究得很给力,主要以看博文为学习方式.以下是我对java的反射机制所产生的一些感悟,希望各位童鞋看到失误之处不吝指出.受到各位指教之处,如若让小生好好感动, ...
- Java:反射
初识Java反射机制: 从上面的描述可以看出Java的反射机制使得Java语言可以在运行时去认识在编译时并不了解的类/对象的信息,并且能够调用相应的方法或修改属性的值.Java反射机制的核心就是允许在 ...
- Java中反射机制和Class.forName、实例对象.class(属性)、实例对象getClass()的区别
一.Java的反射机制 每个Java程序执行前都必须经过编译.加载.连接.和初始化这几个阶段,后三个阶段如下图: 其中
- java笔记--反射进阶之总结与详解
一.反射进阶之动态设置类的私有域 "封装"是Java的三大特性之一,为了能更好保证其封装性,我们往往需要将域设置成私有的, 然后通过提供相对应的set和get方法来操作这个域.但是 ...
- java笔记--反射机制之基础总结与详解
一.反射之实例化Class类的5种方式: java的数据类型可以分为两类,即引用类型和原始类型(即基本数据类型). 对于每种类型的对象,java虚拟机会实例化不可变的java.lang.Class对象 ...
- Java中反射的三种常用方式
Java中反射的三种常用方式 package com.xiaohao.test; public class Test{ public static void main(String[] args) t ...
随机推荐
- 经典sql总结(1)
1.表示info 信息,字段为Id和res,如何得到如下结果
- 【Java基础】Java内部类
什么是内部类 把类定义在其他类的内部,这个类就被称为内部类. 内部类的分类 内部类分为两种,分别为成员内部类和局部内部类: 成员内部类:和成员变量和成员方法定义在同级 局部内部类:和局部变量定义在同级 ...
- http 2.0
http2.0 待学习整理 http://www.zhihu.com/question/34074946
- 【转】bootbox自定义dialog、confirm、alert样式,以及基本设置方法setDefaults中可用参数
<html> <head> <meta charset="utf-8"> <meta name="viewport" ...
- Installutil.exe 注册exe
进入到C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe目录下,然后输入Installutil.exe 文件路径实现注册 I ...
- Java-Web监听器
在WEB端实现监听实质: 实现一系列的监听接口(实现相应的接口,覆写各接口中相应的方法,在相应的事件触发的时候会执行自己的监听器中的覆写的方法,在各个方法中完成自己想要的操作,从而实现了监听) 监听- ...
- 《Spring技术内幕》学习笔记17——Spring HTTP调用器实现远程调用
1.Spring中,HTTPInvoker(HTTP调用器)是通过基于HTTP协议的分布式远程调用解决方案,和java RMI一样,HTTP调用器也需要使用java的对象序列化机制完成客户端和服务器端 ...
- Data Structure导论的导论
DataStructure是一组互相之间存在一种或多种特定关系的数据的组织方式和它们在计算机内的存储方式,以及定义在该数据上的一组操作. 从以上定义可知,数据结构是研究数据的组织.存储方式及其操作的学 ...
- C#中多线程 委托的使用
背景: 什么是多线程?我们在建立以个C#项目时,往往会在Form1上添加控件,然后写代码,初 学者都是在重复这个过程,其实这个过程是单线程的,可以理解为只有“main”主线程,有 的时候往往需要同时 ...
- WPF中的StackPanel、WrapPanel、DockPanel
一.StackPanel StackPanel是以堆叠的方式显示其中的控件 1.可以使用Orientation属性更改堆叠的顺序 Orientation="Vertical" 默认 ...