本文目录
一,认识反射
二,Class类对象实例化
demo_Class类对象实例化
package cn.reflect.demo;
class Member_A{
public Member_A(){
System.out.println("[构造方法]实例化Member类对象。");
}
@Override
public String toString(){
return "[方法覆写]Member类对象信息输出。";
}
}
public class 反射Class类实例化对象 {
public static void main(String[] args) throws Exception{
Class<?> clazz=Class.forName("cn.reflect.demo.Member_A");
Object obj=clazz.getDeclaredConstructor().newInstance();
System.out.println(obj);
}
}
运行结果
class cn.reflect.demo.Member
class cn.reflect.demo.Member
class cn.reflect.demo.Member
三,反射机制与对象实例化
demo_反射Class类实例化对象
package cn.reflect.demo;
class Member_A{
public Member_A(){
System.out.println("[构造方法]实例化Member类对象。");
}
@Override
public String toString(){
return "[方法覆写]Member类对象信息输出。";
}
}
public class 反射Class类实例化对象 {
public static void main(String[] args) throws Exception{
Class<?> clazz=Class.forName("cn.reflect.demo.Member_A");
Object obj=clazz.getDeclaredConstructor().newInstance();
System.out.println(obj);
}
}
运行结果
[构造方法]实例化Member类对象。
[方法覆写]Member类对象信息输出。
demo_反射与工厂设计模式
package cn.reflect.demo;
interface IMessage{
public void send();
}
class CloudMessage implements IMessage{
@Override
public void send(){
System.out.println("[云消息]");
}
}
class NetMessage implements IMessage{
@Override
public void send(){
System.out.println("[网络消息]");
}
}
class Factory{
private Factory(){}
public static<T> T getInstance(String classname){
T instance=null;
try {
//通过包路径实例化Class,再反射实例化对象。最后强制向上转型。
instance=(T)Class.forName(classname).getDeclaredConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return instance;
}
}
public class 反射与工厂设计模式 {
public static void main(String[] args) {
IMessage mes=Factory.getInstance("cn.reflect.demo.CloudMessage");
mes.send();
}
}
运行结果
[云消息]
demo_反射与单例设计模式
package cn.reflect.demo;
class Singleton{
private static Singleton instance=null;
private Singleton(){
System.out.println("["+Thread.currentThread().getName()+"]"+"实例化Singleton对象");
}
public static Singleton getInstance(){
if(instance==null){
synchronized(Singleton.class){//没有同步操作将导致线程同步问题
//该处同步代码块,两次判断instance是否为null,且不使用同步方法是因为:同步方法效率慢,同步代码块牺牲小,两次判断可以尽可能的降低同步操作对程序运行效率的影响
if(instance==null){
instance=new Singleton();
}
}
}
return instance;
}
public void Print(){
System.out.println("你好世界!");
}
}
public class 反射与单例设计模式 {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
new Thread(()->{
Singleton.getInstance().Print();
},"线程-"+i).start();
}
}
}
运行结果
[线程-0]实例化Singleton对象
你好世界!
你好世界!
你好世界!
四,反射机制与类操作
demo_反射获取类结构信息
package cn.reflect.demo;
interface IMessageService{
public void send();
}
interface IChannelService{
public boolean connect();
}
abstract class AbstractBase{}
class Mail extends AbstractBase implements IMessageService,IChannelService{
@Override
public boolean connect() {
return true;
}
@Override
public void send() {
if(this.connect()){
System.out.println("[消息发送]你好世界");
}
}
}
public class 反射获取类结构信息 {
public static void main(String[] args) {
Class<?> clazz=Mail.class;
Package pack=clazz.getPackage();
System.out.println(pack.getName());
Class<?> parent=clazz.getSuperclass();
System.out.println(parent.getName());
Class<?> claz[]=clazz.getInterfaces();
for (Class<?> temp : claz) {
System.out.println(temp.getName());
}
}
}
运行结果
cn.reflect.demo
cn.reflect.demo.AbstractBase
cn.reflect.demo.IMessageService
cn.reflect.demo.IChannelService
demo_反射调用构造方法
package cn.reflect.demo;
import java.lang.reflect.Constructor;
class Mail_A{
private String msg;
private Mail_A(){}
public Mail_A(int a,int b,int c){}
public Mail_A(String msg){
System.out.println("[构造方法]调用Mail_A类单参构造方法,实例化对象");
this.msg=msg;
}
@Override
public String toString() {
return "[toString()方法覆写]消息内容:"+this.msg;
}
}
public class 反射调用构造方法 {
public static void main(String[] args)throws Exception {
Class<?> clazz=Mail_A.class;
Constructor<?>[] con=clazz.getConstructors();
for (Constructor<?> temp : con) {
System.out.println(temp);
}
Constructor<?> cons=clazz.getConstructor(String.class);
Object obj=cons.newInstance("你好世界");
System.out.println(obj);
}
}
运行结果
public cn.reflect.demo.Mail_A(java.lang.String)
public cn.reflect.demo.Mail_A(int,int,int)
[构造方法]调用Mail_A类单参构造方法,实例化对象
[toString()方法覆写]消息内容:你好世界
demo_反射调用方法
package cn.reflect.demo;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
class Person_B{
private String name;
public Person_B(){}
public Person_B(String name){
this.name=name;
}
public void setName(String name)throws Exception{
this.name=name;
}
public String getName(){
return this.name;
}
}
public class 反射调用方法 {
public static void main(String[] args) throws Exception{
Class<?> clazz=Person_B.class;
Method methods[]=clazz.getDeclaredMethods();
for (Method temp : methods) {
int mod=temp.getModifiers();
System.out.print(Modifier.toString(mod)+" ");
System.out.print(temp.getReturnType()+" ");
System.out.print(temp.getName()+"(");
Class<?> params[]=temp.getParameterTypes();
for(int i=0;i<params.length;i++){
System.out.print(params[i].getName()+" arg-"+i);
if(i<params.length-1){
System.out.println(",");
}
}
System.out.print(")");
Class<?> exp[]=temp.getExceptionTypes();
if(exp.length>0){
System.out.print(" throws ");
}
for(int x=0;x<exp.length;x++){
System.out.print(exp[x].getName());
if(x<exp.length-1){
System.out.print(",");
}
}
System.out.println();
}
//----------------------------------------------------
Object obj=clazz.getDeclaredConstructor().newInstance();
Method setMethod=clazz.getDeclaredMethod("setName", String.class);
setMethod.invoke(obj, "张三");
Method getMethod=clazz.getDeclaredMethod("getName");
System.out.println(getMethod.invoke(obj));
}
}
运行结果
public class java.lang.String getName()
public void setName(java.lang.String arg-0) throws java.lang.Exception
张三
demo_反射调用成员属性
package cn.reflect.demo;
import java.lang.reflect.Field;
interface Iann{
public static final String NAME="你给我力giao";
}
abstract class AbstractAnn{
protected static final String BASE="我太难了";
private String str = "hello";
}
class Message extends AbstractAnn implements Iann{
private String name;
public int age;
}
public class 反射调用成员属性 {
public static void main(String[] args)throws Exception {
Class<?> clazz=Message.class;
{
Field fields[]=clazz.getFields();
for (Field temp : fields) {
System.out.println(temp.getName());
}
}
System.out.println("---------------------");
{
Field fields[]=clazz.getDeclaredFields();
for (Field field : fields) {
System.out.print(field.getType().getSimpleName()+" ");
System.out.print(field.getName());
System.out.println();
}
}
System.out.println("---------------------");
{
Object obj=clazz.getDeclaredConstructor().newInstance();
Field field=clazz.getDeclaredField("name");
field.setAccessible(true);
field.set(obj, "张三");
System.out.println(field.get(obj));
}
}
}
运行结果
age
NAME
---------------------
String name
int age
---------------------
张三
demo_Unsafe工具类
//在JDK1.8中 Unsafe类已被删除
package cn.reflect.demo;
import java.lang.reflect.Field;
class Singleton{
private Singleton(){
System.out.println("********Singleton类构造*********");
}
public void print(){
System.out.println("你好世界");
}
}
public class Unsafe工具类 {
public static void main(String[] args) {
Field field=Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
Unsalf unsalf=(Unsalf)field.get();
Singleton instance=(Singleton)unsafe.allocateInstance(Singleton.class);
instance.print();
}
}
运行结果
********Singleton类构造*********
你好世界
五,反射与简单Java类
demo_属性自动赋值实现思路
package cn.reflect.demo;
class Emp{
private String ename;
private String job;
public void setEname(String ename){
this.ename=ename;
}
public void setJob(String job){
this.job=job;
}
public String getEname(){
return this.ename;
}
public String getJob(){
return this.job;
}
}
class ClassInstanceFactory{
private ClassInstanceFactory(){}
/**
* 实例化对象的创建方法,输入的属性设置value为:“属性:内容|属性:内容”
* @param clazz 获取需要反射实例化的类
* @param value 获取设置属性的内容
* @return 返回一个设置好成员属性的java类对象
*/
public static <T> T create(Class<?> clazz,String value){
/*核心代码*/return null;
}
}
public class 属性自动赋值实现思路 {
public static void main(String[] args) {
String value="ename:张三|jod:程序员";
Emp emp=ClassInstanceFactory.create(Emp.class, value);
System.out.println("姓名:"+emp.getEname()+",工作:"+emp.getJob());
}
}
demo_单级属性赋值
package cn.reflect.demo;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
class Emp_B{
private String ename;
private String job;
public void setEname(String ename){
this.ename=ename;
}
public void setJob(String job){
this.job=job;
}
public String getEname(){
return this.ename;
}
public String getJob(){
return this.job;
}
}
class StringUtils {
private StringUtils(){};
public static String initcap(String str){
if(str==null||"".equals(str)){
return str;
}
if(str.length()==1){
return str.toUpperCase();
}else{
return str.substring(0,1).toUpperCase()+str.substring(1);
}
}
}
class BeanUtils{
private BeanUtils(){}
public static void setValue(Object obj,String value){
String results[]=value.split("\\|");
for (int i = 0; i < results.length; i++) {
String attval[]=results[i].split("\\:");
try{
Field field = obj.getClass().getDeclaredField(attval[0]);
Method method=obj.getClass().getDeclaredMethod("set"+StringUtils.initcap(attval[0]), field.getType());
method.invoke(obj, attval[1]);
}catch (Exception e){}//跳过错误项进行后续的赋值
}
}
}
class ClassInstanceFactory_B{
private ClassInstanceFactory_B(){}
/**
* 实例化对象的创建方法,输入的属性设置value为:“属性:内容|属性:内容”
* @param clazz 获取需要反射实例化的类
* @param value 获取设置属性的内容
* @return 返回一个设置好成员属性的java类对象
*/
public static <T> T create(Class<?> clazz,String value){
try{
Object obj=clazz.getDeclaredConstructor().newInstance();
BeanUtils.setValue(obj, value);
return (T)obj;
}catch (Exception e){
return null;
}
}
}
public class 单级属性赋值 {
public static void main(String[] args) {
String value="ename:张三|job:程序员";
Emp_B emp=ClassInstanceFactory_B.create(Emp_B.class, value);
System.out.println("姓名:"+emp.getEname()+",工作:"+emp.getJob());
}
}
运行结果
姓名:张三,工作:程序员
demo_设置多种数据类型
package cn.reflect.demo;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
class Emp_C{//修改Emp类:添加多个数据类型与setter getter
private String ename;
private String job;
private Double salary;
private Integer age;
private Date hiredate;
public void setEname(String ename){
this.ename=ename;
}
public void setJob(String job){
this.job=job;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public String getEname(){
return this.ename;
}
public String getJob(){
return this.job;
}
}
class StringUtils_C {
private StringUtils_C(){};
public static String initcap(String str){
if(str==null||"".equals(str)){
return str;
}
if(str.length()==1){
return str.toUpperCase();
}else{
return str.substring(0,1).toUpperCase()+str.substring(1);
}
}
}
class BeanUtils_C{//修改Bean类:增加处理多种数据类型的方法
private BeanUtils_C(){}
public static void setValue(Object obj,String value){
String results[]=value.split("\\|");
for (int i = 0; i < results.length; i++) {
String attval[]=results[i].split(":");
try{
Field field = obj.getClass().getDeclaredField(attval[0]);
Method method=obj.getClass().getDeclaredMethod("set"+StringUtils_C.initcap(attval[0]), field.getType());
Object convertValue=BeanUtils_C.convertAttributeValue(field.getType().getName(), attval[1]);
method.invoke(obj, convertValue);
}catch (Exception e){}//跳过错误项进行后续的赋值
}
}
public static Object convertAttributeValue(String type,String value){
if("long".equals(type)||"java.lang.Long".equals(type)){
return Long.parseLong(value);
}else if("int".equals(type)||"java.lang.Integer".equals(type)){
return Integer.parseInt(value);
}else if("double".equals(type)||"java.lang.Double".equals(type)){
return Double.parseDouble(value);
}else if("java.util.Date".equals(type)){
System.out.println(value);
SimpleDateFormat sdf=null;
if(value.matches("\\d{4}-\\d{1,2}-\\d{1,2}")){
sdf=new SimpleDateFormat("yyyy-MM-dd");
}else if(value.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")){
sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}else{
return new Date();
}
try {
return sdf.parse(value);
} catch (Exception e) {
return new Date();
}
}else{
return value;
}
}
}
class ClassInstanceFactory_C{
private ClassInstanceFactory_C(){}
/**
* 实例化对象的创建方法,输入的属性设置value为:“属性:内容|属性:内容”
* @param clazz 获取需要反射实例化的类
* @param value 获取设置属性的内容
* @return 返回一个设置好成员属性的java类对象
*/
public static <T> T create(Class<?> clazz,String value){
try{
Object obj=clazz.getDeclaredConstructor().newInstance();
BeanUtils_C.setValue(obj, value);
return (T)obj;
}catch (Exception e){
return null;
}
}
}
public class 设置多种数据类型 {//修改客户端:增加传入信息
public static void main(String[] args) {
String value="ename:张三|job:程序员|salary:10000|age:20|hiredate:2023-8-3";
Emp_C emp=ClassInstanceFactory_C.create(Emp_C.class, value);
System.out.println("姓名:"+emp.getEname()+",工作:"+emp.getJob()+",薪水:"+emp.getSalary()+",年龄:"+emp.getAge()+",雇用时间:"+emp.getHiredate());
}
}
运行结果
2023-8-3
姓名:张三,工作:程序员,薪水:10000.0,年龄:20,雇用时间:Thu Aug 03 00:00:00 CST 2023
demo_联级对象实例化与属性赋值
package cn.reflect.demo;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
class Company{
private String name;
private Date createdate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
}
class Dept{
private String dname;
private String loc;
private Company company;//级联对象
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
}
class Emp_D{
private String ename;
private String job;
private Double salary;
private Integer age;
private Date hiredate;
private Dept dept;//级联对象
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public void setEname(String ename){
this.ename=ename;
}
public void setJob(String job){
this.job=job;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public String getEname(){
return this.ename;
}
public String getJob(){
return this.job;
}
}
class StringUtils_D {//用于处理setter方法名称格式
private StringUtils_D(){};
public static String initcap(String str){
if(str==null||"".equals(str)){
return str;
}
if(str.length()==1){
return str.toUpperCase();
}else{
return str.substring(0,1).toUpperCase()+str.substring(1);
}
}
}
class BeanUtils_D{//用于处理对象实例化与属性赋值
private BeanUtils_D(){}
public static void setValue(Object obj,String value){//用于级联对象实例化与级联对象属性赋值,普通对象属性赋值
String results[]=value.split("\\|");
for (int i = 0; i < results.length; i++) {
String attval[]=results[i].split(":");
try{
if(attval[0].contains(".")){//有.说明输入数据存在级联关系,需要判断级联的各对象是否被实例化
String temp[]=attval[0].split("\\.");
Object currentObject=obj;
for(int y=0;y<temp.length-1;y++){//判断并进行级联对象实例化
Method getMethod=currentObject.getClass().getDeclaredMethod("get"+StringUtils_D.initcap(temp[y]));
//invoke方法当调用方法的对象不存在时返回null
Object tempObject=getMethod.invoke(currentObject);
if(tempObject==null){//级联对象实例化
Field field=currentObject.getClass().getDeclaredField(temp[y]);
Method method=currentObject.getClass().getDeclaredMethod("set"+StringUtils_D.initcap(temp[y]), field.getType());
Object newObject=field.getType().getDeclaredConstructor().newInstance();
method.invoke(currentObject, newObject);
currentObject=newObject;
}else{
currentObject=tempObject;//[类似递归]tempObject不为空声明这一级的级联对象以被实例化,那么将tempObject赋值给currentObject用于下一次从该级为起点向后判断“dept(以被判断).company(待判断).name”
}//for循环结束后的currentObject是“.”分隔的倒数第二项
}
//由于输入格式为:“dept.company.name:阿里巴巴”,属性内容总是和“.”分隔的倒数第二项匹配所以要跳出上面的循环进行级联对象属性赋值
//级联对象属性赋值:
Field field = currentObject.getClass().getDeclaredField(temp[temp.length-1]);
Method setmethod=currentObject.getClass().getDeclaredMethod("set"+StringUtils_D.initcap(temp[temp.length-1]), field.getType());
Object convertValue=BeanUtils_D.convertAttributeValue(field.getType().getName(), attval[1]);
setmethod.invoke(currentObject, convertValue);
}else{
//普通属性赋值:
Field field = obj.getClass().getDeclaredField(attval[0]);
Method method=obj.getClass().getDeclaredMethod("set"+StringUtils_D.initcap(attval[0]), field.getType());
Object convertValue=BeanUtils_D.convertAttributeValue(field.getType().getName(), attval[1]);
method.invoke(obj, convertValue);
}
}catch (Exception e){}//跳过错误项进行后续的赋值
}
}
public static Object convertAttributeValue(String type,String value){//修改Bean类:增加处理多种数据类型的方法
if("long".equals(type)||"java.lang.Long".equals(type)){
return Long.parseLong(value);
}else if("int".equals(type)||"java.lang.Integer".equals(type)){
return Integer.parseInt(value);
}else if("double".equals(type)||"java.lang.Double".equals(type)){
return Double.parseDouble(value);
}else if("java.util.Date".equals(type)){
SimpleDateFormat sdf=null;
if(value.matches("\\d{4}-\\d{1,2}-\\d{1,2}")){
sdf=new SimpleDateFormat("yyyy-MM-dd");
}else if(value.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}")){
sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}else{
return new Date();
}
try {
return sdf.parse(value);
} catch (Exception e) {
return new Date();
}
}else{
return value;
}
}
}
class ClassInstanceFactory_D{//用于创建基础实例化对象,调用Bean类进行属性赋值
private ClassInstanceFactory_D(){}
/**
* 实例化对象的创建方法,输入的属性设置value为:“属性:内容|属性:内容”
* @param clazz 获取需要反射实例化的类
* @param value 获取设置属性的内容
* @return 返回一个设置好成员属性的java类对象
*/
public static <T> T create(Class<?> clazz,String value){
try{
Object obj=clazz.getDeclaredConstructor().newInstance();
BeanUtils_D.setValue(obj, value);
return (T)obj;
}catch (Exception e){
return null;
}
}
}
public class 级联对象实例化与赋值 {
public static void main(String[] args){
String value="ename:张三|job:程序员|salary:10000|age:20|hiredate:2023-8-5|dept.dname:开发部|dept.loc:上海|dept.company.name:阿里巴巴|dept.company.createdate:1989-10-21";
Emp_D emp=ClassInstanceFactory_D.create(Emp_D.class, value);
System.out.println("姓名:"+emp.getEname()+",工作:"+emp.getJob()+",薪水:"+emp.getSalary()+",年龄:"+emp.getAge()+",雇用时间:"+emp.getHiredate());
System.out.println("从属部门:"+emp.getDept().getDname()+",坐落于:"+emp.getDept().getLoc());
System.out.println("部门从属公司:"+emp.getDept().getCompany().getName()+",创立时间:"+emp.getDept().getCompany().getCreatedate());
}
}
运行结果
姓名:张三,工作:程序员,薪水:10000.0,年龄:20,雇用时间:Sat Aug 05 00:00:00 CST 2023
从属部门:开发部,坐落于:上海
部门从属公司:阿里巴巴,创立时间:Sat Oct 21 00:00:00 CST 1989
六,ClassLoader类加载器
demo_类加载器简介
package cn.reflect.demo;
class A{}
public class 类加载器简介 {
public static void main(String[] args) {
A a=new A();
//自定义类使用的加载器
System.out.println(a.getClass().getClassLoader());//AppClassLoader
System.out.println(a.getClass().getClassLoader().getParent());//ExtClassLoader/PlatformClassLoader
System.out.println(a.getClass().getClassLoader().getParent().getParent());//null:由C++语言编写的类加载器不是java写的所以只能以null返回
//系统类使用的加载器
String str="hello";
System.out.println(str.getClass().getClassLoader());//null说明系统类使用的加载器和自定义类使用的加载器不同
}
}
运行结果
jdk.internal.loader.ClassLoaders$AppClassLoader@1f89ab83
jdk.internal.loader.ClassLoaders$PlatformClassLoader@6e8dacdf
null
null
demo_自定义ClassLoader类(较难)
(1)ClassLoader类:
package cn.reflect.demo;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class 自定义ClassLoader类 extends ClassLoader{//继承ClassLoader类是为了调用其中的defineClass方法
public Class<?> loadData(String CLASS_PATH)throws Exception{
byte[] data=this.loadClassData(CLASS_PATH);
if(data!=null){
return super.defineClass(null, data, 0, data.length);
}
return null;
}
public byte[] loadClassData(String CLASS_PATH)throws Exception{
InputStream input=null;
ByteArrayOutputStream bos=null;
byte[]data=null;
int intData=0;
try {
bos=new ByteArrayOutputStream();
input=new FileInputStream(new File(CLASS_PATH));
while((intData=input.read())!=-1){
bos.write(intData);
}
data=bos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(bos!=null){
bos.close();
}
if(input!=null){
input.close();
}
}
return data;
}
}
(2)测试类
package cn.reflect.demo;
import java.lang.reflect.Method;
import cn.reflect.demo.自定义ClassLoader类;
public class 自定义ClassLoader类_测试类 {
public static void main(String[] args) throws Exception{
自定义ClassLoader类 classLoader=new 自定义ClassLoader类();
Class<?> clazz=classLoader.loadData("cn.reflect.demo.Messages");
Object obj=clazz.getDeclaredConstructor().newInstance();
Method method=clazz.getDeclaredMethod("send");
method.invoke(obj);
}
}
(3)加载类(cn.reflect.demo.Messages)
package cn.reflect.demo;
public class Messages
{ public void send(){
System.out.println("hello");
}
}
运行结果
hello
七,反射与代理设计模式
demo_动态代理设计模式
package cn.reflect.demo;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface IMessage_A{
public void send();
}
class MessageReal_A implements IMessage_A{
@Override
public void send() {
System.out.println("消息发送");
}
}
class MessageProxy_A implements InvocationHandler{//动态代理生成类
private Object realTarget;//保存真实业务对象
/**
* 通过Proxy类的newProxyInstance方法来绑定真实业务对象,并生成临时代理类
* @param realTarget 真实业务对象
* @return 真实业务对象对应的代理类
*/
public Object bind(Object realTarget){
this.realTarget=realTarget;
return Proxy.newProxyInstance(realTarget.getClass().getClassLoader(), realTarget.getClass().getInterfaces(), this);
}
public boolean connect(){
System.out.println("[开始连接]");
return true;
}
public void close(){
System.out.println("[关闭连接]");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnData=null;
if(this.connect()){
returnData=method.invoke(this.realTarget, args);
this.close();
}
return returnData;
}
}
public class 动态代理设计模式 {
public static void main(String[] args) throws Exception{
IMessage_A msg =(IMessage_A) new MessageProxy_A().bind(new MessageReal_A());
msg.send();
}
}
运行结果
[开始连接]
消息发送
[关闭连接]
demo_CGLIB实现动态代理设计模式
package cn.reflect.demo;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
class Message_CGLIB{
public void send(){
System.out.println("hello!");
}
}
class CGLIB_Proxy implements MethodInterceptor{
private Object target;
public CGLIB_Proxy(Object target){
this.target=target;
}
public boolean connect(){
System.out.println("begin");
return true;
}
public void close(){
System.out.println("over");
}
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy arg3) throws Throwable {
Object returnData=null;
if(this.connect()){
returnData=method.invoke(this.target,args);
close();
}
return returnData;
}
}
public class CGLIB实现动态代理设计模式 {
public static void main(String[] args) {
Message_CGLIB realMes=new Message_CGLIB();
Enhancer enhancer =new Enhancer();
enhancer.setSuperclass(realMes.getClass());//假定一个父类
enhancer.setCallback(new CGLIB_Proxy(realMes));
Message_CGLIB proxyMes=(Message_CGLIB)enhancer.create();
proxyMes.send();
}
}
运行结果
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by net.sf.cglib.core.ReflectUtils$2 (file:/E:/%e5%90%8e%e7%ab%af/%e7%bc%96%e7%a8%8b%e8%af%ad%e8%a8%80/Java/java_odd/%e6%89%a9%e5%b1%95%e5%8c%85/cglib-nodep-2.2.2.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of net.sf.cglib.core.ReflectUtils$2
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
begin
hello!
over
八,反射与Annotation
demo_反射获得Annotation信息
package cn.reflect.demo;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
@FunctionalInterface
@Deprecated
interface IMessage_Ann{
public void send(String msg);
}
@SuppressWarnings("serial")
class MessageImple_Ann implements IMessage_Ann,Serializable{
@Override
public void send(String msg) {
System.out.println("hello");
}
}
public class 反射获得Annotation信息 {
public static void main(String[] args) throws Exception{
{//获取接口上的Annnotation
Annotation ann[]=IMessage_Ann.class.getAnnotations();
for (Annotation temp : ann) {
System.out.println(temp);
}
}
System.out.println("---------------------------");
{//获取类上的Annotation
Annotation ann[]=MessageImple_Ann.class.getAnnotations();
for (Annotation temp : ann) {
System.out.println(temp);
}
}
System.out.println("---------------------------");
{//获取方法上的Annotation
Method method = MessageImple_Ann.class.getDeclaredMethod("send", String.class);
Annotation ann[]=method.getAnnotations();
for (Annotation temp : ann) {
System.out.println(temp);
}
}
}
}
运行结果
@java.lang.FunctionalInterface()
@java.lang.Deprecated(forRemoval=false, since="")
---------------------------
---------------------------
demo_自定义Annotation
package cn.reflect.demo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface DefaultAnnotation{
public String title();
public String url()default "hello";
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface DefaultAnnotations{
public String value();
}
class UseAnnotation{
@DefaultAnnotation(title="hi ")
@DefaultAnnotations(" world")
public void send(String msg){
System.out.println("[消息发送]:"+msg);
}
}
public class 自定义Annotation {
public static void main(String[] args)throws Exception {
Method method = UseAnnotation.class.getMethod("send", String.class);
DefaultAnnotation ann=method.getDeclaredAnnotation(DefaultAnnotation.class);
DefaultAnnotations anns=method.getDeclaredAnnotation(DefaultAnnotations.class);
String str=ann.title()+ann.url()+anns.value();
method.invoke(UseAnnotation.class.getDeclaredConstructor().newInstance(), str);
}
}
运行结果
[消息发送]:hi hello world
demo_Annotation整合工厂类
package cn.reflect.demo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface IMessage_AnnFac{
public void send(String msg);
}
class CloudMessage_AnnFac implements IMessage_AnnFac{
@Override
public void send(String msg) {
System.out.println("[云消息]"+msg);
}
}
class NetMessage_AnnFac implements IMessage_AnnFac{
@Override
public void send(String msg) {
System.out.println("[网络消息]"+msg);
}
}
class MessageProxy_AnnFac implements InvocationHandler{
private Object target;
public Object bind(Object target){
this.target=target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(), this);
}
public boolean connect() {
System.out.println("[开始连接]");
return true;
}
public void close(){
System.out.println("[结束连接]");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try{
if(this.connect()){
return method.invoke(target, args);
}else {
throw new Exception("[连接出错]");
}
}finally{
this.close();
}
}
}
class Factory_AnnFac{//工厂类:通过输入的class对象,生成一个对应的动态代理类
private Factory_AnnFac(){}
public static <T> T getInstance(Class <T> clazz){
try{
return (T) new MessageProxy_AnnFac().bind(clazz.getDeclaredConstructor().newInstance());
}catch(Exception e){
return null;
}
}
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface UseMessage{
public Class<?> clazz();
}
@UseMessage(clazz=NetMessage_AnnFac.class)//利用Annotation来设置需要操作的接口子类
class MessageService_AnnFac{//利用MessageService类来对接Factory类,实现对外操作的隐藏
private IMessage_AnnFac mess;
public MessageService_AnnFac(){
UseMessage use=MessageService_AnnFac.class.getAnnotation(UseMessage.class);
this.mess=(IMessage_AnnFac)Factory_AnnFac.getInstance(use.clazz());
}
public void send(String msg){
this.mess.send(msg);
}
}
public class Annotation整合工厂类 {
public static void main(String[] args) {
MessageService_AnnFac messageService=new MessageService_AnnFac();
messageService.send("hello");
}
}
运行结果
[开始连接]
[网络消息]hello
[结束连接]
本文完,欢迎访问或关注我的【Java SE】专栏。