java 反射(Reflection)-干货
发布时间:2020-12-14 06:32:06 所属栏目:Java 来源:网络整理
导读:看了很多关于java 反射的文章,自己把所看到的总结一下。对自己,对他人或多或少有帮助吧。 首先来看看 Oracle里面对Reflection的描述: Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of
看了很多关于java 反射的文章,自己把所看到的总结一下。对自己,对他人或多或少有帮助吧。 首先来看看Oracle里面对Reflection的描述: Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind,reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.
JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。 简单的讲:
再简单一点的讲:
举个例子: Java是面向对象语言,我们可以把老虎,狮子等具有相同性质的动物归类(抽象)为猫科动物,他们具有牙齿,胡须等一些属性。同时具有吃肉()的动作。 同样的道理,我们所接触到的类Class,也可以把他们抽象出来,有类名,成员变量,方法等。 那么既然能够把类看做是对象,那么java就可以对其进行处理。
获取Class有一下三种方法: 1. 使用Class类的forName静态方法
Class.forName("com.mysql.jdbc.Driver" }
2. 直接获取某一个对象的class Class> klass = . Class> classInt = Integer.TYPE;
3. 调用某个对象的getClass()方法 Demo demo= }
?下面是一个完整的Demo展示Java Reflection的操作:
main(String[] args)
System.out.println("==============================================="
System.out.println("==============================================="
System.out.println("==============================================="
System.out.println("==============================================="
System.out.println("==============================================="
System.out.println("==============================================="
System.out.println("==============================================="
System.out.println("==============================================="
Person person = System.out.println("Demo1: 包名: " + person.getClass().getPackage().getName() + "," + "完整类名: " +
Demo2()
Class> class1 = Class> class2 =
class1 = Class.forName("com.b510.hongten.test.reflex.Person" System.out.println("Demo2:(写法1) 包名: " + class1.getPackage().getName() + "," + "完整类名: " +
class2 = Person. System.out.println("Demo2:(写法2) 包名: " + class2.getPackage().getName() + "," + "完整类名: " +
|