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. linux 已有目录挂载磁盘

    1.查看当前硬盘使用状况: [root@gluster_node1 ~]# df -h Filesystem            Size  Used Avail Use% Mounted on / ...

  2. 关于npoi不能导入07以上版本的Excel

    因为在npoi版本中1.几之下的版本的不能导入07版本以上的excel是因为在其中的封装的方法中不支持, 所以很简单我们去网站上下一新的版本的npoi就是了,最好是新出来的2.1.1版本的就完全zhi ...

  3. POJ1502: MPI Maelstrom

    红果果的dijstra算法应用,这里采用邻接表存储图 小插曲:while(scanf("%d",&n))提交时内存超限,改成while(scanf("%d&quo ...

  4. Apple LLVM 6.0 Warning: profile data may be out of date

    I have no clue what this meant, so I googled the problem. I only ended up with some search results s ...

  5. NULL指针 Void* 和野指针

    在C和C++的语言中常常有这几个概念: NULL指针.空指针.Void *指针.野指针(Wild Pointer)甚至垂悬指针(Dangling Pointer). 1.NULL指针,一般用于指向一个 ...

  6. Dllimport函数時无法在Dll中找到的入口点

    今天開發客戶提供的一個dll時出現無法找到入口點問題,由於客戶也不能明確說明dll,所以一時不知道如何下手,經查詢後找到可通過vs自帶的dumpbin.exe查看. Dumpbin.exe位于 VS的 ...

  7. CSS入门基础

    认识CSS 传统HTML设计网页版面的缺点 CSS的特点 CSS的排版样式 13.1 认识CSS CSS的英文全名是Cascading Style Sheets,中文可翻译为串接式排版样式,并且CSS ...

  8. Installutil.exe 注册exe

    进入到C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe目录下,然后输入Installutil.exe 文件路径实现注册   I ...

  9. ASP.NET MVC- Model- An Introduction to Entity Framework for Absolute Beginners

    Introduction This article introduces Entity Framework to absolute beginners. The article is meant fo ...

  10. NoSQL 数据库产品学习总结(一)

    NoSQL 数据库产品学习总结(一) 本篇文章共分为四个章节,会陆续整理下 Memcached.Redis.tair.mongodb.hbase.SequoiaDB. Cassandra的相关知识. ...