Java高级语法笔记-反射机制(Reflection) (1)
生活随笔
收集整理的這篇文章主要介紹了
Java高级语法笔记-反射机制(Reflection) (1)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
反射機制:在C/C++里面是沒有的。
反射機制是Java的一個非常重要的機制。一些著名的應用框架都使用了此機制。
java.lang.Class它是Java語法的一個基礎類,用于描述一個class對象。在文件系統中,class以文件的形式存在 Student.class在運行時的JVM中,該*.class文件被加載到內存中成為一個對象,對象的類型就是java.lang.Class。
代碼如下:
Student.java
package my;public class Student {private int id;private String name;private String phone;public Student(){}public Student(int id, String name, String phone){this.id = id;this.name = name;this.phone = phone;}@Overridepublic String toString(){return "(" + id + "," + name + "," + phone + ")";}public int getId(){return id;}public void setId(int id){this.id = id;}public String getName(){return name;}public void setName(String name){this.name = name;}public String getPhone(){return phone;}public void setPhone(String phone){this.phone = phone;}@Overridepublic boolean equals(Object obj){// 與一個Student對象比較if(this.getClass().isInstance(obj)){Student other = (Student) obj;return other.id == this.id;}// 與一個String對象比較 if(String.class.isInstance(obj)){String other = (String)obj;return other.equals(this.name);}// 與一個Integer對象比較if(Integer.class.isInstance(obj)){Integer other = (Integer)obj;return this.id == other;}return false;} }HelloWorld.java package my;import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;public class HelloWorld {public static void test1(Object obj){Class cls = Student.class;if(cls.isInstance(obj)){// 判斷obj是不是Student類型System.out.println("is an instance of Student");}else {System.out.println("is not an instance of Student");}}public static void test2(Object obj){String clsName = obj.getClass().getName();if(clsName.equals("my.Student")){System.out.println("is an instance of Student");}}public static void main(String[] args){ Class cls = Student.class; System.out.println("Name: " + cls.getName());// Student obj = new Student(); // Class cls2 = obj.getClass();Object obj = new Student();test1( new Integer(123));Student s1 = new Student(1000, "qiuqiu", "13254565789");Student s2 = new Student(10001, "tuitui", "13562352365");if(s1.equals(1000)){System.out.println("equal");}else{System.out.println("not equal");}} }
運行結果如下:
總結
以上是生活随笔為你收集整理的Java高级语法笔记-反射机制(Reflection) (1)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux指令解压rpm,dpkg r
- 下一篇: Java高级语法笔记-向上层抛出异常