博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java反射机制
阅读量:7219 次
发布时间:2019-06-29

本文共 4408 字,大约阅读时间需要 14 分钟。

在以前的文章中有简单介绍过,但没有深入了解,补充一下。

反射:

反射是 JVM 在运行时才动态加载类或调用方法/访问属性,它不需要事先(写代码的时候或编译期)知道运行对象是谁。主要功能是在运行时判断任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判断任意一个类所具有的成员变量和方法(通过反射甚至可以调用private方法);在运行时调用任意一个对象的方法

getName():获得类的完整名字。newInstance():通过类的不带参数的构造方法创建这个类的一个对象getSuperClass():这个类型的直接超类的全限定名 isInterface():这个类型是类类型还是接口类型 getTypeParamters():这个类型的访问修饰符 getInterfaces():任何直接超接口的全限定名的有序列表 得到构造器的方法Constructor getConstructor(Class[] params) -- 获得使用特殊的参数类型的公共构造函数,Constructor[] getConstructors() -- 获得类的所有公共构造函数Constructor getDeclaredConstructor(Class[] params) -- 获得使用特定参数类型的构造函数(与接入级别无关)Constructor[] getDeclaredConstructors() -- 获得类的所有构造函数(与接入级别无关)获得字段信息的方法Field getField(String name) -- 获得命名的公共字段Field[] getFields() -- 获得类的所有公共字段Field getDeclaredField(String name) -- 获得类声明的命名的字段,包括private 声明的和继承类Field[] getDeclaredFields() -- 获得类声明的所有字段获得方法信息的方法Method getMethod(String name, Class[] params) -- 使用特定的参数类型,获得命名的公共方法,name参数指定方法的名字,parameterTypes 参数指定方法的参数类型。Method[] getMethods() -- 获得类的所有公共方法Method getDeclaredMethod(String name, Class[] params) -- 使用特写的参数类型,获得类声明的命名的方法Method[] getDeclaredMethods() -- 获得类声明的所有方法,包括private 声明的和继承类

反射步骤:

获取一个对象

  • 获取类的 Class 对象实例
    Class cla = Class.forName("cn.spleated.Car");
  • 根据 Class 对象实例获取 Constructor 对象
    Constructor CarConstructor = cla.getConstructor();
  • 使用 Constructor 对象的 newInstance 方法获取反射类对象
    Object appleObj = CarConstructor.newInstance();
import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;import static java.lang.Class.forName;public class ConstructorDemo {    public ConstructorDemo(){}    public ConstructorDemo(int a,int b){        System.out.println("a="+a+"\nb="+b);    }    public static void  main(String args[]) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {            Class cls = forName("ConstructorDemo");            Class partypes[]=new Class[2];            partypes[0] = Integer.TYPE;            partypes[1] = Integer.TYPE;            Constructor ct = cls.getConstructor(partypes);            Object arg[] = new Object[2];            arg[0] = new Integer(37);            arg[1] = new Integer(14);            Object ret = ((Constructor) ct).newInstance(arg);    }}

调用某一个方法

  • 获取方法的 Method 对象
    Method setPriceMethod = cla.getMethod("setPrice", int.class);
  • 利用 invoke 方法调用方法
    setPriceMethod.invoke(appleObj, 14);
import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class Methodemo {    public int add(int a,int b){        return a+b;    }    public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {        Class cls = Class.forName("Methodemo");        Class pro[] = new Class[2];        pro[0] = Integer.TYPE;        pro[1] = Integer.TYPE;        Method me = cls.getMethod("add",pro);        Methodemo metobj = new Methodemo();        Object arg[] = new Object[2];        arg[0] = new Integer(13);        arg[1] = new Integer(25);        Object reobj = me.invoke(metobj,arg);        Integer ret = (Integer) reobj;        System.out.println(ret.intValue());    }}

Java语言执行系统命令

由JVM创建一个本机进程,加载对应的指令到进程的地址空间中,然后执行该指令。

java.lang.Runtime.getRuntime().exec() java.lang.ProcessBuilder.start()方法,其实就是创建一个进程的方法。具体可查看

跟一下代码流程
  • 进入java.lang.Runtime类中,Runtime类的构造器是private修饰的,无法直接获得Runtime类的实例,只能通过getRuntime()来间接获取一个Runtime类的实例
  • 跟进exec()方法

  • exec()底层代码是调用了ProcessBuilder类
  • ProcessBuilder类代码中,ProcessBuilder类用start方法创建进程。调用java.lang.ProcessImpl类的start方法,实现创建本机进程,执行系统命令的功能
  • 跟进ProcessImpl类,他是继承自Process类final类
  • 查看他的构造器,是private修饰的,无法直接在java.lang包外,直接调用ProcessImpl类。
  • 跟进ProcessImpl类start方法,最后是返回了一个ProcessImpl 类的实例
  • 流程图

分析下上篇文章的通过getRuntime().exec()调用计算机

import java.lang.reflect.InvocationTargetException;public class POC {    public static void main(String args[]) throws  IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {        Object runtime=Class.forName("java.lang.Runtime")                .getMethod("getRuntime",new Class[]{})                .invoke(null);        Class.forName("java.lang.Runtime")                .getMethod("exec", String.class)                .invoke(runtime,"calc.exe");    }}
  • 获取Runtime类的Class对象
  • 分别获取Runtime类Class对象的getRuntime方法和exec方法的Method对象
  • 利用getRuntime方法的Method对象,进行invoke调用,获得Runtime对象实例
  • 利用exec方法的Method对象,进行invoke调用,执行系统命令

参考文献:

转载地址:http://xqxym.baihongyu.com/

你可能感兴趣的文章
记一次源码分析
查看>>
php版本引起的const问题
查看>>
js实现60s倒计时效果
查看>>
【POJ 2176】Folding
查看>>
redis的过期策略以及内存淘汰机制
查看>>
阿牛的EOF牛肉串
查看>>
随笔2013/2/13
查看>>
笨办法32循环和列表
查看>>
java序列化
查看>>
谈谈NITE 2的第一个程序HandViewer
查看>>
VS2008 未响应 假死
查看>>
html5、css3及响应式设计入门
查看>>
Win10還原成最乾淨的狀態
查看>>
Java_InvokeAll_又返回值_多个线程同时执行,取消超时线程
查看>>
SaltStack作业
查看>>
单例设计
查看>>
springboot+缓存
查看>>
/*10个filter的属性*/ ---毛玻璃效果
查看>>
折半查找习题解答
查看>>
51单片机的P1
查看>>