java 尋找類的所有子類

來源:互聯網
上載者:User

標籤:bin   classname   ext   pat   java   目錄   檔案   類型   net   

package _02;import java.io.File;import java.net.URL;public class MainTest_FindAllSubClass {public static void main(String[] args) {Class<?> clazz = MainTest_FindAllSubClass.class;// 定位到當前的包路徑// URL url = Toy.class.getResource("");// 定位到bin目錄URL url = clazz.getResource("/");System.out.println(url);String fileName = url.getFile();System.out.println(fileName);String pathName = fileName.replaceFirst("/", "");System.out.println(pathName);File rootFile = new File(pathName);setSubList(rootFile, rootFile.getPath() + "\\", clazz);}/** * 遍曆bin目錄下所有檔案 * 若是檔案夾,則遞迴將檔案夾內檔案添加到檔案數組 * 若是檔案,則將檔案載入並強制類型轉換為要尋找子類的父類,轉換無異常,說明載入類是父類的子類 * (當遍曆到類自身時,此處認為也屬於子類,當然這是我的一廂情願,我肯定不告訴你--〉我嫌麻煩。。 * 不過我還是加上了判斷--〉自我要求比較高。。 * ) * */public static <T> void setSubList(File rootFile, String parentDirectory,Class<T> parentClass) {if (rootFile.isDirectory()) {File[] files = rootFile.listFiles();for (File file : files) {setSubList(file, parentDirectory, parentClass);}} else {String className = null;try {if (rootFile.getPath().indexOf(".class") != -1) {className = rootFile.getPath().replace(parentDirectory, "").replace(".class", "").replace("\\", ".");Class<?> classObject = Class.forName(className);classObject.asSubclass(parentClass);// 要麼是子類,要麼是類本身if (! className.equals(parentClass.getCanonicalName())){System.out.println(className + " extends " + parentClass);}else{System.out.println(className + " is " + parentClass);}}} catch (ClassNotFoundException e) {System.err.println("can not find " + className);} catch (ClassCastException e) {System.err.println(className + " do not extends " + parentClass);}}}}// 測試class Sub1 extends MainTest_FindAllSubClass {}//測試class Sub2 extends MainTest_FindAllSubClass {}

  

java 尋找類的所有子類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.