Java反射机制概述
概念

反射相关的主要API
* java.lang.Class:代表一个类
* java.lang.reflect.Method:代表类的方法
* java.lang.reflect.Field:代表类的成员变量
* java.lang.reflect.Constructor:代表类的构造器
基本使用
// 反射操作
@Test
public void test1() throws Exception {
Class clas = Person.class; // 禁止class作为变量名
//1.通过反射,创建Person类的对象
Constructor constructor = clas.getConstructor(String.class, int.class);
Object obj = constructor.newInstance("Tom", 12);
Person person = (Person)obj;
System.out.println(person); // Person{name='Tom', age=12}
//2.通过反射,调用对象指定的属性、方法
// 调用属性
Field age = clas.getDeclaredField("age");
age.set(person,30);
System.out.println(person); // Person{name='Tom', age=30}
// 调用方法
Method show = clas.getDeclaredMethod("show");
show.invoke(person); // 你好,xxxx
System.out.println("*******************************");
//通过反射,可以调用Person类的私有结构的。比如:私有的构造器、方法、属性
//调用私有的构造器
Constructor constructor1 = clas.getDeclaredConstructor(String.class);
constructor1.setAccessible(true);
Object obj1 = constructor1.newInstance("jack");
Person person1 = (Person)obj1;
System.out.println(person1); // Person{name='jack', age=0}
//调用私有的属性
Field name = clas.getDeclaredField("name");
name.setAccessible(true);
name.set(person1,"jacklove");
System.out.println(person1); // Person{name='jacklove', age=0}
//调用私有的方法
Method showNation = clas.getDeclaredMethod("showNation", String.class);
showNation.setAccessible(true);
showNation.invoke(person1,"中华"); // 我的国籍是:中华
}
理解Class类并获取Class实例
关于java.lang.Class类的理解
* 类的加载过程:
程序经过javac.exe命令以后,会生成一个或多个字节码文件(.class结尾)。
接着我们使用java.exe命令对某个字节码文件进行解释运行。相当于将某个字节码文件加载到内存中。
此过程就称为类的加载。加载到内存中的类,我们就称为运行时类,此运行时类,就作为Class的一个实例。
* 换句话说,Class的实例就对应着一个运行时类。
* 加载到内存中的运行时类,会缓存一定的时间。在此时间之内,我们可以通过不同的方式来获取此运行时类。
* Class类是Reflection的根源,针对任何你想动态加载、运行的类,唯有先获得相应的Class对象
获取Class类的实例(四种方法)
//获取Class的实例的方式(前三种方式需要掌握)
@Test
public void test3() throws ClassNotFoundException {
//方式一:调用运行时类的属性:.class
Class clas1 = Person.class;
//方式二:通过运行时类的对象,调用getClass()
Class clas2 = (new Person()).getClass();
//方式三:调用Class的静态方法:forName(String classPath)
Class<?> clas3 = Class.forName("reflection_zgc.Person");
//方式四:使用类的加载器:ClassLoader (了解)
ClassLoader classLoader = Person.class.getClassLoader();
Class clas4 = classLoader.loadClass("reflection_zgc.Person");
System.out.println(clas1); // class reflection_zgc.Person
System.out.println(clas1 == clas2); // true
System.out.println(clas1 == clas3); // true
System.out.println(clas1 == clas4); // true
}
类的加载与ClassLoader的理解
目录:https://blog.youkuaiyun.com/admin741admin/article/details/109146291
具体:https://blog.youkuaiyun.com/admin741admin/article/details/107944341
使用ClassLoader加载配置文件
@Test
public void test1() throws IOException {
//读取配置文件的方式一:
//此时的文件默认在当前的module下。
// Properties properties = new Properties();
// FileInputStream fis = new FileInputStream("jdbc1.properties");
// properties.load(fis);
// //读取配置文件的方式二:使用ClassLoader
//配置文件默认识别为:当前module的src下
Properties properties = new Properties();
ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
InputStream resourceAsStream = classLoader.getResourceAsStream("jdbc1.properties");
properties.load(resourceAsStream);
String user = properties.getProperty("user");
String password = properties.getProperty("password");
System.out.println("user = " + user + ",password = " + password);
}
中文乱码

创建运行时类的对象
无参构造
/*
newInstance():调用此方法,创建对应的运行时类的对象。内部调用了运行时类的空参的构造器。
要想此方法正常的创建运行时类的对象,要求:
1.运行时类必须提供空参的构造器
2.空参的构造器的访问权限得够。通常,设置为public。
在javabean中要求提供一个public的空参构造器。原因:
1.便于通过反射,创建运行时类的对象
2.便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器
*/
Class<Person> clazz = Person.class;
Person obj = clazz.newInstance();
System.out.println(obj);
有参构造
//1.根据全类名获取对应的Class对象
String name = “atguigu.java.Person";
Class clazz = null;
clazz = Class.forName(name);
//2.调用指定参数结构的构造器,生成Constructor的实例
Constructor con = clazz.getConstructor(String.class,Integer.class);
//3.通过Constructor的实例创建对应类的对象,并初始化类属性
Person p2 = (Person) con.newInstance("Peter",20);
System.out.println(p2);
获取运行时类的完整结构-了解
/*
获取构造器结构
*/
@Test
public void test1(){
Class clazz = Person.class;
//getConstructors():获取当前运行时类中声明为public的构造器
Constructor[] constructors = clazz.getConstructors();
for(Constructor c : constructors){
System.out.println(c);
}
System.out.println();
//getDeclaredConstructors():获取当前运行时类中声明的所有的构造器
Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
for(Constructor c : declaredConstructors){
System.out.println(c);
}
}
/*
获取运行时类的父类
*/
@Test
public void test2(){
Class clazz = Person.class;
Class superclass = clazz.getSuperclass();
System.out.println(superclass);
}
/*
获取运行时类的带泛型的父类
*/
@Test
public void test3(){
Class clazz = Person.class;
Type genericSuperclass = clazz.getGenericSuperclass();
System.out.println(genericSuperclass);
}
/*
获取运行时类的带泛型的父类的泛型
代码:逻辑性代码 vs 功能性代码
*/
@Test
public void test4(){
Class clazz = Person.class;
Type genericSuperclass = clazz.getGenericSuperclass();
ParameterizedType paramType = (ParameterizedType) genericSuperclass;
//获取泛型类型
Type[] actualTypeArguments = paramType.getActualTypeArguments();
// System.out.println(actualTypeArguments[0].getTypeName());
System.out.println(((Class)actualTypeArguments[0]).getName());
}
/*
获取运行时类实现的接口
*/
@Test
public void test5(){
Class clazz = Person.class;
Class[] interfaces = clazz.getInterfaces();
for(Class c : interfaces){
System.out.println(c);
}
System.out.println();
//获取运行时类的父类实现的接口
Class[] interfaces1 = clazz.getSuperclass().getInterfaces();
for(Class c : interfaces1){
System.out.println(c);
}
}
/*
获取运行时类所在的包
*/
@Test
public void test6(){
Class clazz = Person.class;
Package pack = clazz.getPackage();
System.out.println(pack);
}
/*
获取运行时类声明的注解
*/
@Test
public void test7(){
Class clazz = Person.class;
Annotation[] annotations = clazz.getAnnotations();
for(Annotation annos : annotations){
System.out.println(annos);
}
}
/**
* 获取运行时类的方法结构
*/
@Test
public void test1(){
Class clazz = Person.class;
//getMethods():获取当前运行时类及其所有父类中声明为public权限的方法
Method[] methods = clazz.getMethods();
for(Method m : methods){
System.out.println(m);
}
System.out.println();
//getDeclaredMethods():获取当前运行时类中声明的所有方法。(不包含父类中声明的方法)
Method[] declaredMethods = clazz.getDeclaredMethods();
for(Method m : declaredMethods){
System.out.println(m);
}
}
/*
@Xxxx
权限修饰符 返回值类型 方法名(参数类型1 形参名1,...) throws XxxException{}
*/
@Test
public void test2(){
Class clazz = Person.class;
Method[] declaredMethods = clazz.getDeclaredMethods();
for(Method m : declaredMethods){
//1.获取方法声明的注解
Annotation[] annos = m.getAnnotations();
for(Annotation a : annos){
System.out.println(a);
}
//2.权限修饰符
System.out.print(Modifier.toString(m.getModifiers()) + "\t");
//3.返回值类型
System.out.print(m.getReturnType().getName() + "\t");
//4.方法名
System.out.print(m.getName());
System.out.print("(");
//5.形参列表
Class[] parameterTypes = m.getParameterTypes();
if(!(parameterTypes == null && parameterTypes.length == 0)){
for(int i = 0;i < parameterTypes.length;i++){
if(i == parameterTypes.length - 1){
System.out.print(parameterTypes[i].getName() + " args_" + i);
break;
}
System.out.print(parameterTypes[i].getName() + " args_" + i + ",");
}
}
System.out.print(")");
//6.抛出的异常
Class[] exceptionTypes = m.getExceptionTypes();
if(exceptionTypes.length > 0){
System.out.print("throws ");
for(int i = 0;i < exceptionTypes.length;i++){
if(i == exceptionTypes.length - 1){
System.out.print(exceptionTypes[i].getName());
break;
}
System.out.print(exceptionTypes[i].getName() + ",");
}
}
System.out.println();
}
}
/**
* 获取当前运行时类的属性结构
*/
@Test
public void test1(){
Class clazz = Person.class;
//获取属性结构
//getFields():获取当前运行时类及其父类中声明为public访问权限的属性
Field[] fields = clazz.getFields();
for(Field f : fields){
System.out.println(f);
}
System.out.println();
//getDeclaredFields():获取当前运行时类中声明的所有属性。(不包含父类中声明的属性)
Field[] declaredFields = clazz.getDeclaredFields();
for(Field f : declaredFields){
System.out.println(f);
}
}
//权限修饰符 数据类型 变量名
@Test
public void test2(){
Class clazz = Person.class;
Field[] declaredFields = clazz.getDeclaredFields();
for(Field f : declaredFields){
//1.权限修饰符
int modifier = f.getModifiers();
System.out.print(Modifier.toString(modifier) + "\t");
//2.数据类型
Class type = f.getType();
System.out.print(type.getName() + "\t");
//3.变量名
String fName = f.getName();
System.out.print(fName);
System.out.println();
}
}
调用运行时类的指定结构-掌握
getField和getDeclaredField区别:前者要求运行时类中属性声明为public,后者没限制
setAccessible,保证当前属性/方法/构造器是可访问的,一般用于配合getDeclaredxxx使用
/*
不需要掌握
*/
@Test
public void testField() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person) clazz.newInstance();
//获取指定的属性:要求运行时类中属性声明为public
//通常不采用此方法
Field id = clazz.getField("id");
/*
设置当前属性的值
set():参数1:指明设置哪个对象的属性 参数2:将此属性值设置为多少
*/
id.set(p,1001);
/*
获取当前属性的值
get():参数1:获取哪个对象的当前属性值
*/
int pId = (int) id.get(p);
System.out.println(pId);
}
/*
如何操作运行时类中的指定的属性 -- 需要掌握
*/
@Test
public void testField1() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person) clazz.newInstance();
//1. getDeclaredField(String fieldName):获取运行时类中指定变量名的属性
Field name = clazz.getDeclaredField("name");
//2.保证当前属性是可访问的
name.setAccessible(true);
//3.获取、设置指定对象的此属性值
name.set(p,"Tom");
System.out.println(name.get(p));
}
/*
如何操作运行时类中的指定的方法 -- 需要掌握
*/
@Test
public void testMethod() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person) clazz.newInstance();
/*
1.获取指定的某个方法
getDeclaredMethod():参数1 :指明获取的方法的名称 参数2:指明获取的方法的形参列表
*/
Method show = clazz.getDeclaredMethod("show", String.class);
//2.保证当前方法是可访问的
show.setAccessible(true);
/*
3. 调用方法的invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参
invoke()的返回值即为对应类中调用的方法的返回值。
*/
Object returnValue = show.invoke(p,"CHN"); //String nation = p.show("CHN");
System.out.println(returnValue);
System.out.println("*************如何调用静态方法*****************");
// private static void showDesc()
Method showDesc = clazz.getDeclaredMethod("showDesc");
showDesc.setAccessible(true);
//如果调用的运行时类中的方法没有返回值,则此invoke()返回null
// Object returnVal = showDesc.invoke(null);
Object returnVal = showDesc.invoke(Person.class);
System.out.println(returnVal);//null
}
/*
如何调用运行时类中的指定的构造器
*/
@Test
public void testConstructor() throws Exception {
Class clazz = Person.class;
//private Person(String name)
/*
1.获取指定的构造器
getDeclaredConstructor():参数:指明构造器的参数列表
*/
Constructor constructor = clazz.getDeclaredConstructor(String.class);
//2.保证此构造器是可访问的
constructor.setAccessible(true);
//3.调用此构造器创建运行时类的对象
Person per = (Person) constructor.newInstance("Tom");
System.out.println(per);
}
反射的应用:动态代理
静态代理举例
// 统一接口
interface ClothFactory{
void produceCloth();
}
//代理类
class ProxyClothFactory implements ClothFactory{
private ClothFactory clothFactory;
public ProxyClothFactory(ClothFactory clothFactory){
this.clothFactory = clothFactory;
}
@Override
public void produceCloth() {
System.out.println("代理做的事情1");
this.clothFactory.produceCloth();
System.out.println("代理做的事情2");
}
}
// 被代理类
class NikeClothFactory implements ClothFactory{
@Override
public void produceCloth() {
System.out.println("nike的产品");
}
}
public class StaticProxyTest {
public static void main(String[] args) {
ClothFactory clothFactory = new NikeClothFactory();
ProxyClothFactory proxyClothFactory = new ProxyClothFactory(clothFactory);
proxyClothFactory.produceCloth();
// 代理做的事情1
//nike的产品
//代理做的事情2
}
}
动态代理举例+AOP
// 统一接口
interface Human{
String getBelief();
void eat(String food);
}
//被代理类
class SuperMan implements Human{
@Override
public String getBelief() {
return "SuperMan的getBelief方法调用";
}
@Override
public void eat(String food) {
System.out.println("我在吃" + food);
}
}
// 生成代理对象1
class ProxyFactory{
// 调用此方法,返回一个代理类的对象。
public static Object getProxyInstance(Object object) {
MyInvocationHandler myInvocationHandler = new MyInvocationHandler();
myInvocationHandler.bind(object);
// ClassLoader loader, Class<?>[] interfaces, InvocationHandler h
return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),myInvocationHandler);
}
}
// 生成对象2
class MyInvocationHandler implements InvocationHandler{
private Object obj;
public void bind(Object obj){
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Aop
AopUtil aopUtil = new AopUtil();
aopUtil.method1();
// method:即为代理类对象调用的方法,此方法也就作为了被代理类对象要调用的方法
// obj:被代理类的对象
Object invoke = method.invoke(this.obj, args);
aopUtil.method2();
return invoke;
}
}
class AopUtil{
public void method1(){
System.out.println("====================通用方法一====================");
}
public void method2(){
System.out.println("====================通用方法二====================");
}
}
public class ProxyTest {
public static void main(String[] args) {
SuperMan superMan = new SuperMan();
// 生成代理对象
Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan);
String belief = proxyInstance.getBelief();
System.out.println(belief);
proxyInstance.eat("龙虾");
System.out.println("**********************************");
NikeClothFactory nikeClothFactory = new NikeClothFactory();
ClothFactory proxyInstance1 = (ClothFactory) ProxyFactory.getProxyInstance(nikeClothFactory);
proxyInstance1.produceCloth();
// ====================通用方法一====================
//====================通用方法二====================
//SuperMan的getBelief方法调用
//====================通用方法一====================
//我在吃龙虾
//====================通用方法二====================
//**********************************
//====================通用方法一====================
//nike的产品
//====================通用方法二====================
}
}
本文详细介绍了Java反射机制的基本使用,包括通过`Class`类获取实例,操作类的构造器、属性和方法,以及动态代理和AOP示例。重点展示了如何创建对象、调用私有结构和实现动态代理。
7115

被折叠的 条评论
为什么被折叠?



