Java反射学习

在计算机科学中,反射是指计算机程序在运行时(Run time)可以访问、检测和修改它本身状态或行为的一种能力。用比喻来说,反射就是程序在运行的时候能够“观察”并且修改自己的行为。

重点是运行时

在Java中利用反射获得一个Class对象有三种方法:

  1. 通过forName
Class a=Class.forName();
  1. 直接获取某一个类的Class
Class a=Test.Class;
  1. 调用某个对象的getClass方法
Class a=new Test().getClass();

如何应用反射去获得一个对象

使用Class的newInstance方法

Class a=TestClass.class;
//newInstance返回Object,需要转类型
TestClass test=(TestClass)a.newInstance();

或者是通过构造器

Class a=TestClass.class;
Constructor constructor=a.getConstructor();
TestClass test=(TestClass)constructor.newInstance();

区别是如果通过Class的newInstance只能使用默认的无参构造函数,通过构造器的newInstance则可以指定构造函数

Class a=TestClass.class;
Constructor constructor=a.getConstructor(int.class);
Object testa=a.newInstance();
Object testb=constructor.newInstance(100);

通过反射获取类的方法

  1. getMethod()方法
public Method getMethod(String name, Class<?>... parameterTypes)

该方法是获得一个特定的方法,参数是想要获取的方法的名字,然后是这个方法的所有参数的Class对象

Method method=a.getMethod(haha,int.class);
  1. getMethods()方法
    该方法是获取该类的所有public方法,包括其继承类的public方法
  2. getDeclaredMethod()方法
    该方法返回类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。

⚠ getMethods()和getDeclaredMethod()的区别

getMethods()会输出父类的public方法,一直到java.lang.Object
而getDeclaredMethod()只会输出本类的所有方法

class TestA {
    private void testa(){}
    public void testb(){}
}
class TestB extends TestA {
    public void testc(){}
}
public class Main {
    public static void main(String[] args) {
        Class a=TestB.class;
        Method[] methods=a.getMethods();
        Method[] declaredMethods=a.getDeclaredMethods();
        for(Method method:methods) {
            System.out.println(method);
        }
        System.out.println("*******************************");
        for(Method method:declaredMethods) {
            System.out.println(method);
        }
    }
}

输出结果是

public void TestB.testc()
public void TestA.testb()
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
*******************************
public void TestB.testc()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值