JAVA反射基础

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;
对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
核心反射机制:提供了通过程序来访问已装载的类的信息的能力
一个生活中常看到的例子有助于理解我们为什么要用Java的反射机制:你进了一家饭店,你不知道他们都有那些菜,要多少钱。那么你第一件事情是干啥“服务员拿个菜单过来”,然后指着菜单说“我要这个,我要那个”。


具体代码示例参照我的github代码:

https://github.com/jinzhencs/MyJavaBasic/tree/master/src/com/myjavabasic/java/Reflection

————————————————————分割线——————————————————————

反射的问题解答:

1.为什么getDeclaredConstructors()得到的构造函数打印出来是逆序的?

getConstructors()还没验证

答案:jdk1.7官方api解答

  • Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. These are public, protected, default (package) access, and private constructors. The elements in the array returned are not sorted and are not in any particular order . If the class has a default constructor, it is included in the returned array. This method returns an array of length 0 if this Class object represents an interface, a primitive type, an array class, or void. 

————————————————————分割线——————————————————————


2.内部类可以反射嘛?

当然可以,不过写法稍稍不同,是用$符号

com.myjavabasic.java.Reflection.Example.GetterAndSetter$Bea

// 注意内部类反射的时候的写法,下面这个是错误的,会抛出ClassNotFound异常

// com.myjavabasic.java.Reflection.Example.GetterAndSetter.Bea


如果要生成内部类的实例,则

----内部类设置成static

----先实例化一个主类的实例

You need to jump through a few hoops to do this. First, you need to use Class.getConstructor() to find the Constructor object you want to invoke:
Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object. The parameterTypes parameter is an array of Class objects that identify the constructor's formal parameter types, in declared order. If this Class object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.

And then you use Constructor.newInstance():
If the constructor's declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值