Java反射机制-学习笔记2

本文通过多个实例详细介绍了Java反射机制的应用,包括调用其他类的方法、使用getter和setter方法、操作类属性及数组等,展示了如何利用反射进行动态操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【实例8】调用其他类中的方法

package org.zhang.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

interface Chiness{
    void say();
}

class Person implements Chiness{
    public Person(){

    }

    @Override
    public void say() {
        System.out.println("我是中国人");
    }

    public void sayHello(String str,int x){
        System.out.println("Hello, String is: " + str + ", int is: " + x);
    }
}

public class ReflectTest {
    public static void main(String[] args){

        Class<?> personClass = null;
        try {
            personClass = Class.forName("org.zhang.test.Person");
            Method method = personClass.getMethod("say");
            method.invoke(personClass.newInstance());

            Method sayHello = personClass.getMethod("sayHello",String.class,int.class);
            sayHello.invoke(personClass.newInstance(),"你好",25);


        } catch (ClassNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (NoSuchMethodException e){
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (InvocationTargetException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (InstantiationException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }
}

【结果:】 

我是中国人
Hello, String is: 你好, int is: 25


【实例9】调用其他类的getter、setter方法

package org.zhang.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class Person {
    private String name;
    private String sex;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

public class ReflectTest {
    public static void main(String[] args) {
        Class<?> personClass = null;

        try {
            personClass = Class.forName("org.zhang.test.Person");
            Person person = (Person) personClass.newInstance();
            setter(person,"name","xiaozhang");
            setter(person,"sex","男");
            getter(person,"name");
            getter(person,"sex");
        } catch (InstantiationException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IllegalAccessException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ClassNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public static void getter(Object obj, String attr) {
        try {
            Class<?> objClass = obj.getClass();
            String methodName = "get" + attr.substring(0, 1).toUpperCase() + attr.substring(1);
            Method getMethod = objClass.getMethod(methodName);
            System.out.println(getMethod.invoke(obj));

        } catch (NoSuchMethodException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IllegalAccessException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (InvocationTargetException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public static void setter(Object obj, String attr, Object value) {
        try {
            Class<?> objClass = obj.getClass();
            String methodName = "set" + attr.substring(0, 1).toUpperCase() + attr.substring(1);
            Method setMethod = objClass.getMethod(methodName, value.getClass());
            setMethod.invoke(obj,value);

        } catch (NoSuchMethodException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IllegalAccessException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (InvocationTargetException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}
【结果:】 

xiaozhang
男


【实例10】通过反射操作类的属性

public class ReflectTest {
    public static void main(String[] args) {
        Class<?> personClass = null;

        try {
            personClass = Class.forName("org.zhang.test.Person");
            Person person = (Person) personClass.newInstance();
            person.setName("old name");
            person.setSex("male");
            System.out.println(person.getName());

            Field nameField = personClass.getDeclaredField("name");
            nameField.setAccessible(true);
            nameField.set(person,"new name");
            System.out.println(nameField.get(person));

        } catch (InstantiationException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IllegalAccessException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ClassNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (NoSuchFieldException e){
            e.printStackTrace();
        }

    }
}
【结果:】

old name
new name

【实例11】通过反射,操作数组
public class ReflectTest {
    public static void main(String[] args) {
        int [] temp = {1,2,3,4,5};
        Class<?> tempClass = temp.getClass().getComponentType();
        System.out.println("数组类型:" + tempClass.getName());
        System.out.println("数组长度:" + Array.getLength(temp));
        System.out.println("数组的第一个元素:" + Array.get(temp,0));
        Array.set(temp,0,100);
        System.out.println("修改后的第一个元素是:" + Array.get(temp,0));
    }
}
【结果:】

数组类型:int
数组长度:5
数组的第一个元素:1
修改后的第一个元素是:100


【实例12】获取类加载器

public class ReflectTest {
    public static void main(String[] args) {
        Person p = new Person();
        System.out.println(p.getClass().getClassLoader().getClass().getName());
    }
}
【结果:】

sun.misc.Launcher$AppClassLoader
【注:】

java 中有3种类加载器

1、引导类加载器(bootstrap class loader):它用来加载 Java 的核心库,是用原生代码来实现的,并不继承自java.lang.ClassLoader

2、扩展类加载器(extensions class loader):一般在 jre\lib\ext 目录下
3、AppClassLoader:常用,Java中默认加载器







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值