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之反射的应用的更多相关文章

  1. JAVA的反射理解

    1----------------------------反射的概念----------------------------------------------- JAVA的反射机制是在运行状态中,对 ...

  2. java的反射

    JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意方法和属性:这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制. ...

  3. iOS运行时编程(Runtime Programming)和Java的反射机制对比

    运行时进行编程,类似Java的反射.运行时编程和Java反射的对比如下:   1.相同点   都可以实现的功能:获取类信息.属性设置获取.类的动态加载(NSClassFromString(@“clas ...

  4. Java 类反射机制分析

    Java 类反射机制分析 一.反射的概念及在Java中的类反射 反射主要是指程序可以访问.检测和修改它本身状态或行为的一种能力.在计算机科学领域,反射是一类应用,它们能够自描述和自控制.这类应用通过某 ...

  5. java的反射机制

    一.java的反射机制浅谈 最近研究java研究得很给力,主要以看博文为学习方式.以下是我对java的反射机制所产生的一些感悟,希望各位童鞋看到失误之处不吝指出.受到各位指教之处,如若让小生好好感动, ...

  6. Java:反射

    初识Java反射机制: 从上面的描述可以看出Java的反射机制使得Java语言可以在运行时去认识在编译时并不了解的类/对象的信息,并且能够调用相应的方法或修改属性的值.Java反射机制的核心就是允许在 ...

  7. Java中反射机制和Class.forName、实例对象.class(属性)、实例对象getClass()的区别

    一.Java的反射机制   每个Java程序执行前都必须经过编译.加载.连接.和初始化这几个阶段,后三个阶段如下图:   其中

  8. java笔记--反射进阶之总结与详解

    一.反射进阶之动态设置类的私有域 "封装"是Java的三大特性之一,为了能更好保证其封装性,我们往往需要将域设置成私有的, 然后通过提供相对应的set和get方法来操作这个域.但是 ...

  9. java笔记--反射机制之基础总结与详解

    一.反射之实例化Class类的5种方式: java的数据类型可以分为两类,即引用类型和原始类型(即基本数据类型). 对于每种类型的对象,java虚拟机会实例化不可变的java.lang.Class对象 ...

  10. Java中反射的三种常用方式

    Java中反射的三种常用方式 package com.xiaohao.test; public class Test{ public static void main(String[] args) t ...

随机推荐

  1. PL/SQL连接查询数据报错时Dynamic Performance Tables not accessible

    一.产生该提示原因plsql dev在用户运行过程中,要收集用户统计信息,但是由于你现在登录的用户没有访问v$session,v$sesstat and v$statname视图的权限,所以不能收集当 ...

  2. .Net 程序的运行

    1. 用.Net开发的程序运行的某台机器上必须安装.Net FrameWork 2. .Net FrameWork向下兼容的实现 在安装4.0的时候,会把3.5,2.0等低版本的都装上,从而实现向下兼 ...

  3. asp.net mvc3+EF4.1项目实战

    ASP.NET身份验证机制membership入门——配置篇(1) http://www.cnblogs.com/xlb2000/archive/2010/05/10/1729076.html 1.添 ...

  4. (6)s3c2440用I2C接口访问EEPROM

    在前面阅读理解了I2C的官方协议文档后,就拿s3c2440和EEPROM来验证一下. 本来是想用s3c2440的SDA和SCL管脚复用为GPIO来模拟的,但在没有示波器的情况下搞了一周,怎么都出不来, ...

  5. Esper系列(四)Output

    功能 控制Esper事件流计算结果的输入形式.时间点及频率: 格式 1  ";

  6. POJ2478 - Farey Sequence(法雷级数&&欧拉函数)

    题目大意 直接看原文吧.... The Farey Sequence Fn for any integer n with n >= 2 is the set of irreducible rat ...

  7. 问题-[致命错误] Project1.dpr(1): Unit not found: 'System.pas' or binary equivalents (DCU,DPU)

    问题现象:[致命错误] Project1.dpr(1): Unit not found: 'System.pas' or binary equivalents (DCU,DPU) 问题原因:由于删除D ...

  8. JQ限制输入字数,并提示剩余字数

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. 对XML和YAML文件实现I/O操作

    1.文件的打开关闭 XML\YAML文件在OpenCV中的数据结构为FileStorage,打开操作例如: string filename = "I.xml"; FileStora ...

  10. 大数据与可靠性会碰撞出什么样的Spark?

    可靠性工程领域的可靠性评估,可靠性仿真计算,健康检测与预管理(PHM)技术,可靠性试验,都需要大规模数据来进行支撑才能产生好的效果,以往这些数据都是不全并且收集困难,而随着互联网+的大数据时代的来临, ...