欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java基础知识回顾第七篇 - 反射Reflect

程序员文章站 2022-05-28 17:33:04
...

什么是java反射?核心在于一个对动态二字的理解,即:在运行状态中,能动态获取类的属性和方法,以及动态调用对象的属性和方法。

 

反射的作用:一方面用于反编译(.class到.java文件),另一方面用来动态访问对象的属性、方法等。

 

反射机制中主要的类:

java.lang.Class;                

java.lang.reflect.Constructor; 

java.lang.reflect.Field;        

java.lang.reflect.Method;

java.lang.reflect.Modifier;

 

下面贴出一些示例代码:

package com.tu.test.reflect;

 

import java.io.Serializable;

 

public class User implements Serializable{

private static final long serialVersionUID = 9016949872478554542L;

 

public User() {

 

}

public User(String name,int age,String phone){

this.name = name;

this.age = age;

this.phone = phone;

}

 

private String name;

private int age;

private String phone;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

 

}

 

package com.tu.test.reflect;

 

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

import java.lang.reflect.Modifier;

 

public class ReflectTest {

//获取User类型

public static void getUser() throws Exception{

/**1、获取类**/

//获取类的第一种方法

Class clz1 = Class.forName("com.tu.test.reflect.User");

//获取类的第二种方法(java中每个类型都有class属性)

Class clz2 = User.class;

//获取类的第三种方法(java中任何一个对象都有getClass()方法)

User user = new User();

Class clz3 = user.getClass();

 

/**2、创建对象**/

Object userObj = clz1.newInstance();

 

/**3、获取类的所有属性、方法等信息**/

Field[] fields = clz1.getDeclaredFields();

StringBuilder fieldSb = new StringBuilder();

for (Field field : fields) {

fieldSb.append(Modifier.toString(field.getModifiers())).append(" ");

fieldSb.append(field.getType().getName()).append(" ");

fieldSb.append(field.getName()).append(" ");

fieldSb.append("\n");

}

System.out.println("User类的所有属性信息:" + fieldSb.toString());

 

Method[] methods = clz1.getDeclaredMethods();

StringBuilder methodSb = new StringBuilder();

for (Method method : methods) {

methodSb.append(Modifier.toString(method.getModifiers())).append(" ");

methodSb.append(method.getReturnType().getName()).append(" ");

methodSb.append(method.getName()).append(" ");

 

Class<?>[] paramClzs = method.getParameterTypes();

methodSb.append("(");

for (Class<?> paramClz : paramClzs) {

methodSb.append(paramClz.getName());

}

methodSb.append(method.getParameterTypes()).append(")");

methodSb.append("\n");

}

System.out.println("User类的所有方法信息:" + methodSb.toString());

 

Constructor[] constructors = clz1.getConstructors();

for (Constructor constructor : constructors) {

System.out.println("构造方法:" + constructor.getName());

}

 

/**4、获取特定属性**/

Field name = clz1.getDeclaredField("name");

name.setAccessible(true);//反射机制可打破java封装

name.set(userObj, "wuhoujian");

System.out.println("My name is : " + name.get(userObj));

}

 

public static void main(String[] args) {

try {

getUser();

} catch (Exception e) {

e.printStackTrace();

}

}

}

 

输出结果:

User类的所有属性信息:private static final long serialVersionUID 

private java.lang.String name 

private int age 

private java.lang.String phone 

 

User类的所有方法信息:public int getAge ([Ljava.lang.Class;@19bb25a)

public void setAge (int[Ljava.lang.Class;@da6bf4)

public java.lang.String getPhone ([Ljava.lang.Class;@1e58cb8)

public void setPhone (java.lang.String[Ljava.lang.Class;@179935d)

public java.lang.String getName ([Ljava.lang.Class;@b9e45a)

public void setName (java.lang.String[Ljava.lang.Class;@3ef810)

 

构造方法:com.tu.test.reflect.User

构造方法:com.tu.test.reflect.User

My name is : wuhoujian

 

补充一个示例:

package com.ali.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * Created by hjwue on 2016/11/24.
 */
public class DumpMethods {
    public static void main(String[] args) {
        try {
            Class myClass = Class.forName("java.util.HashMap");

System.out.println("Show all constructors:");
Constructor[] constructors = myClass.getDeclaredConstructors();
System.out.println("The size of all constructors is:" + constructors.length);
Arrays.asList(constructors).forEach(constructor -> System.out.println(constructor.toString()));

System.out.println("Show all public constructors:");
Constructor[] publicConstructors = myClass.getConstructors();
System.out.println("The size of all constructors is:" + publicConstructors.length);
Arrays.asList(publicConstructors).forEach(publicConstructor -> System.out.println(publicConstructor.toString()));

System.out.println("Show all fields:");
Field[] fields = myClass.getDeclaredFields();
System.out.println("The size of all fields is : " + fields.length);
Arrays.asList(fields).forEach(field -> System.out.println(field.toString()));

System.out.println("Show all public fields:");
Field[] publicFields = myClass.getFields();
System.out.println("The size of all public fields is : " + publicFields.length);
Arrays.asList(publicFields).forEach(publicField -> System.out.println(publicField.toString()));

System.out.println("Show all methods:");
Method[] methods = myClass.getDeclaredMethods();
System.out.println("The size of all method is : " + methods.length);
Arrays.asList(methods).forEach((m -> System.out.println(m.toString())));

System.out.println("Show all public methods:");
Method[] publicMethods = myClass.getMethods();
System.out.println("The size of all public method is : " + publicMethods.length);
Arrays.asList(publicMethods).forEach(publicMethod -> System.out.println(publicMethod.toString()));
} catch(Exception e){
            e.printStackTrace();
}
    }
}

 

注:关于上面为提到的操作方法,参考URL:http://tool.oschina.net/apidocs/apidoc?api=jdk-zh

API文档是一个很好的老师,大家平时要多查阅一下。

相关标签: Java基础 反射