JAVA基礎學習篇之反射

20170405發表於2020-08-28

  這塊程式碼如果將class檔案刪除後,第一次執行成功,第二次執行也許會成功也許會報錯,這是因為記憶體中還有class檔案。多執行幾次就會報錯 找不到class檔案

  import cn.chen.pojo.Student;

  import java.io.File;

  public class Test {

  public static void main(String[] args) {

  Student student=new Student();

  File file=new File("E:\\java\\Reflection\\out\\production\\Reflection\\cn\\chen\\pojo\\Student.class");

  if (file.exists()){

  file.delete();

  }

  Class aClass = student.getClass();

  System.out.println(aClass);

  }

  }

  2.獲取class物件內容資訊

  2.1.獲取Class物件的三種方式  

  package cn.chen.demo;

  import cn.chen.pojo.Student;

  //獲取Class物件的三種方式

  public class Demo1 {

  public static void main(String[] args) throws ClassNotFoundException {

  //第一種直接.class獲取

  Class studentClass = Student.class;

  System.out.println(studentClass);

  //第二種透過Object類中的getClass方法獲取

  Student student=new Student();

  Class aClass = student.getClass();

  System.out.println(aClass);

  //第三種透過Class.forName("全限定類名")方法獲取

  Class aClass1 = Class.forName("cn.chen.pojo.Student");

  System.out.println(aClass1);

  }

  }


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69979119/viewspace-2715530/,如需轉載,請註明出處,否則將追究法律責任。

相關文章