Hello,大家好!我是程序員阿飛!今天主要給大家分享一下框架基礎學習——反射。
一、Class類的使用
1、在面向對象的世界裏,萬事萬物皆對象。
注意:java語言中,靜態的成員、普通數據類型不是對象。
類是對象,類是java.lang.Class類的實例對象。
Foo foo1 = new Foo();//Foo的實例對象
任何一個類都是Class的實例對象,這個實例對象有三種表示方式:
Class c1 = Foo.class;
Class c2 = foo1.getClass();
Class c3 = null; c3 = Class.forName("com.imooc.reflect.Foo");
萬事萬物皆對象,類也是對象,是Class類的示例對象,這個對象我們稱之爲該類的類類型。
二、Java動態加載類
Class.forName("類的全稱")
不僅表示了類的類類型,還表示了動態加載類。
請大家區分編譯、運行
編譯時時刻加載類是靜態加載類,運行時加載類是動態加載類。
注意:
new 創建對象是靜態加載類,在編譯時刻就需要加載所有的可能使用的類。
通過動態加載類可以解決此問題。
class Officer{
public static void main(String[] args){
if("word".equals(args[0])){
Word word = new Word();
word.start();
}
if("excel".equals(args[0])){
Excel excel = new Excel();
excel.start();
}
}
}
class OfficeBetter{
public static void main(String[] args){
try{
//動態加載類,在運行時加載
Class c = Class.forName(args[0]);
//通過類類型,創建該類對象
OfficeAble oa = (OfficeAble)c.newInstance();
oa.start();
}catch(Exception e){
e.printStackTrace();
}
}
}
class Word implements OfficeAble{
public void start(){
system.out.printIn("word------");
}
}
class Excel implements OfficeAble{
public void start(){
system.out.printIn("excel------");
}
}
//總結:如果只有Word類,直接編譯Office類,則後臺報錯,提示找不到Excel類;使用了動態加載類,則不需要每次都重新編譯OfficeBetter類。
三、Java獲取方法信息
public class ClassUtil{
public static void printClassMessage(Object obj){
//獲取類的信息
Class c = obj.getClass();
//獲取類的名稱
System.out.printIn("類的名稱:"+c.getName());
/*
* Method類,方法對象表
* 一個成員方法就是一個Method的對象
* getMethod()方法獲取所有的public的函數,包括父類繼承來的
* getDeclaredMethods(); 獲取所有類的申明的方法
*/
Method[] ms = c.getMethods();
for(int i=0;i<ms.length;i++){
//得到方法的返回值類型的類類型
Class returnType = ms[i].getReturnType();
System.out.printIn(returnType.getName()+" ");
//得到方法的名稱
System.out.print(ms[i].getName()+"(");
//獲取參數類型---得到的是參數列表的類型的類類型
Class[] paramTypes = ms[i].getParameterTypes();
for(Class class1:paramTypes){
System.out.print(class1.getName()+",");
}
System.out.print(")");
}
}
}
package com.wnf.reflect;
public class ClassDemo01 {
public static void main(String[] args) {
String name = "Hello World!";
ClassUtil.printClassMessage(name);
ClassDemo02 demo2 = new ClassDemo02();
ClassUtil.printClassMessage(demo2);
}
}
四、Java獲取成員變量構造函數信息
成員變量也是對象
java.lang.reflect.Filed
Filed類封裝了關於成員變量的操作
getFileds()方法獲取的是所有的public的成員變量的信息
getDeclaredFileds獲取的是該類自己聲明的成員變量的信息
Filed[] fs = c.getDeclaredFileds();
for(Filed filed:fs){
//得到成員變量的類型的類類型
Class filedType = filed.getType();
String typeName = fileType.getName();
//得到成員變量的名稱
String filedName = filed.getName();
System.out.printLn(typeName+""+filedName);
}
public static void printFieldMessage(Object obj) {
//獲取成員變量的信息
Class c = obj.getClass();
Field[] fs = c.getFields();
for(Field field : fs){
Class fieldType = field.getType();
String typeName= fieldType.getSimpleName();
String fieldName = field.getName();
System.out.println(typeName+" "+fieldName);
}
}
//getConstructors()獲取public的構造函數
//getDeclaredConstructors()獲取該類自己聲明的構造函數
public static void printConMessage(Object obj){
//獲取該類的構造函數
Class c = obj.getClass();
Constructor[] cr = c.getConstructors();
for (Constructor constructor : cr) {
System.out.print(constructor.getName()+"(");
Class[] paramTypes = constructor.getParameterTypes();
for (int j=0; j<paramTypes.length;j++) {
if(j==paramTypes.length-1){
System.out.print(paramTypes[j].getSimpleName());
}else{
System.out.print(paramTypes[j].getSimpleName()+",");
}
}
System.out.println(")");
}
}
五、Java方法反射的基本操作
方法的反射
1、如何獲取某個方法
方法的名稱和方法的參數列表才能唯一決定某個方法
2、方法反射的操作
method.invoke(對象
,參數列表)
package com.imooc.reflect;
import java.lang.reflect.Method;
public class MethodDemo1 {
public static void main(String[] args) {
//要獲取print(int ,int )方法 1.要獲取一個方法就是獲取類的信息,獲取類的信息首先要獲取類的類類型
A a1 = new A();
Class c = a1.getClass();
/*
* 2.獲取方法 名稱和參數列表來決定
* getMethod獲取的是public的方法
* getDelcaredMethod自己聲明的方法
*/
try {
//Method m = c.getMethod("print", new Class[]{int.class,int.class});
Method m = c.getMethod("print", int.class,int.class);
//方法的反射操作
//a1.print(10, 20);方法的反射操作是用m對象來進行方法調用 和a1.print調用的效果完全相同
//方法如果沒有返回值返回null,有返回值返回具體的返回值
//Object o = m.invoke(a1,new Object[]{10,20});
Object o = m.invoke(a1, 10,20);
System.out.println("==================");
//獲取方法print(String,String)
Method m1 = c.getMethod("print",String.class,String.class);
//用方法進行反射操作
//a1.print("hello", "WORLD");
o = m1.invoke(a1, "hello","WORLD");
System.out.println("===================");
// Method m2 = c.getMethod("print", new Class[]{});
Method m2 = c.getMethod("print");
// m2.invoke(a1, new Object[]{});
m2.invoke(a1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class A{
public void print(){
System.out.println("helloworld");
}
public void print(int a,int b){
System.out.println(a+b);
}
public void print(String a,String b){
System.out.println(a.toUpperCase()+","+b.toLowerCase());
}
}
六、通過反射了解集合泛型的本質
package com.imooc.reflect;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class MethodDemo4 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
ArrayList<String> list1 = new ArrayList<String>();
list1.add("hello");
//list1.add(20);錯誤的
Class c1 = list.getClass();
Class c2 = list1.getClass();
System.out.println(c1 == c2);
//反射的操作都是編譯之後的操作
/*
* c1==c2結果返回true說明編譯之後集合的泛型是去泛型化的
* Java中集合的泛型,是防止錯誤輸入的,只在編譯階段有效,
* 繞過編譯就無效了
* 驗證:我們可以通過方法的反射來操作,繞過編譯
*/
try {
Method m = c2.getMethod("add", Object.class);
m.invoke(list1, 20);//繞過編譯操作就繞過了泛型
System.out.println(list1.size());
System.out.println(list1);
/*for (String string : list1) {
System.out.println(string);
}*///現在不能這樣遍歷
} catch (Exception e) {
e.printStackTrace();
}
}
}