Java--反射
2019-04-03 本文已影响0人
二妹是只猫
反射
定义: java反射机制是在运行状态中
,对于任意一个类
,都能够知道
这个类的所有属性和方法;
对于任意一个对象
,都能够调用
它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为java的反射机制
使用:Class.forname("绝对路径")
类:Robot:
package com.interview.javabasic.reflect;
public class Robot {
private String name;
public void sayHi(String helloSentence){
System.out.println(helloSentence + " " + name);
}
private String throwHello(String tag){
return "Hello " + tag;
}
static {
System.out.println("Hello Robot");
}
}
反射:
public class ReflectSample {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
Class rc = Class.forName("com.interview.javabasic.reflect.Robot");
Robot r = (Robot) rc.newInstance();
System.out.println("Class name is " + rc.getName());
Method getHello = rc.getDeclaredMethod("throwHello", String.class);
getHello.setAccessible(true);
Object str = getHello.invoke(r, "Bob");
System.out.println("getHello result is " + str);
Method sayHi = rc.getMethod("sayHi", String.class);
sayHi.invoke(r, "Welcome");
Field name = rc.getDeclaredField("name");
name.setAccessible(true);
name.set(r, "Alice");
sayHi.invoke(r, "Welcome");
System.out.println(System.getProperty("java.ext.dirs"));
System.out.println(System.getProperty("java.class.path"));
}
}
- Class.forname获取到类
- newInstance()通过调用构造器创建该对象
- setAccessible非公共方法需要设置
- getDeclaredMethod获取该对象所有方法(没有继承方法),getMethod获取该对象所有公有方法(包括基础的公有方法)
- invoke jdk的动态代理执行对象方法
- getDeclaredField获取所有属性
输出如下:
Class name is com.yunche.reflect.Robot
throwHello result is Hello Bob
Welcome null
sayHi result is null
Welcome Alice