Day22_8 Java学习之反射、多线程

目录

一、反射

反射之操作成员方法

反射之操作成员变量  

二、多线程

多线程的概述

Thread 线程类

 线程休眠


一、反射

  • 反射之操作成员方法

解析:

1.反射操作成员方法的目的:操作Method对象来调用成员方法

2.使用method类进行操作,类型中每个方法都是一个Method类的对象。

1.Method类与Class对象中常用方法

1.1Method getMethod(String name,Class...args);
    作用: 根据方法名和参数类型获得对应的方法对象,只能获得public的

1.2Method getDeclaredMethod(String name,Class...args);
    作用: 根据方法名和参数类型获得对应的方法对象,包括非public的【只能获取本类中的一个】

1.3Method[] getMethods();
   作用:获得类中的所有成员方法对象,返回数组,只能获得public修饰的且包含父类的

1.4Method[] getDeclaredMethods();
   作用: 获得类中的所有成员方法对象,返回数组,只获得本类的,包括非public的方法【只能获取本类中所有】

 1.5Object invoke(Object obj, Object... args)
    obj:调用方法所使用的对象,如果是静态方法可以传入null
    args:调用方法时传递的参数【实参】
    
    作用:返回值就是该方法对象调用后的返回值,如果是无返回值方法固定返回null
    
1.6void setAccessible(true) 作用:如果是非public方法,就得调用该方法设置为可访问。
    设置"暴力访问"——是否取消权限检查,true取消权限检查,false表示不取消

代码使用演示:

package com.feisi.week7.day1;

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

public class Test {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // 创建student类的Class对象
        Class<Student> studentClass = Student.class;
        Student student = new Student();

        // 使用原来类的实例对象传入,调用方法 抽象类中的普通私有方法怎么调用呢 好像通过反射也调用不了,因为无法创建该类的实例化对象
        // 使用Class对象创建成员方法对象
        // 获取被public修饰的方法
        Method method = studentClass.getMethod("show");
        System.out.println(method);
        method.invoke(student);
        // 静态普通方法
        Method method1 = studentClass.getMethod("show1");
        method1.invoke(null);

        // 保护静态方法
        Method method2 = studentClass.getDeclaredMethod("show2");
        method2.setAccessible(true);
        method2.invoke(null);

        // 一次性获得多个方法的对象 建议使用下面的方法获取多个,有效避免的报异常的情况
        Method[] declaredMethods = studentClass.getDeclaredMethods();
        
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值