1.Class物件的getClasses()方法取得的是該類別中所有的公共的內部類,以及從父類,父介面繼承來的內部類別。 getinterfaces()方法傳回類別繼承的所有介面。
import javax.print.attribute.standard.PrinterInfo; interface HasBatteries{} interface Waterproof{} interface ShootsThings{} class Toy{ Toy(){} Toy(int i){} } class FancyToy extends Toy implements HasBatteries,Waterproof,ShootsThings{ public FancyToy() { // TODO 自动生成的构造函数存根 super(1); } } public class ToyTest { public static void main(String[] args){ Class class1=null; try{ class1=class1.forName("FancyToy"); }catch (ClassNotFoundException e) { // TODO: handle exception } printInfo(class1); Class[] faces=class1.getInterfaces(); for(int i=0;i<faces.length;i++){ printInfo(faces[i]); } Class cy=class1.getSuperclass(); Object cObject=null; try{ cObject=cy.newInstance(); }catch (Exception e) { // TODO: handle exception } printInfo(cObject.getClass()); } static void printInfo(Class cc){ System.out.println("Class name:"+cc.getName()+" is interface? "+cc.isInterface()); } }
2.Class物件的forName()使用時傳遞的類別名稱classname參數是需要全名的,不能只加類別名,例如包名.類別名,java.lang.String。
import javax.print.attribute.standard.PrinterInfo; interface HasBatteries{} interface Waterproof{} interface ShootsThings{} class Toy{ Toy(){} Toy(int i){} } class FancyToy extends Toy implements HasBatteries,Waterproof,ShootsThings{ public FancyToy() { // TODO 自动生成的构造函数存根 super(1); } } public class ToyTest { public static void main(String[] args){ Class class1=null; try{ class1=class1.forName("FancyToy"); }catch (ClassNotFoundException e) { // TODO: handle exception } printInfo(class1); Class[] faces=class1.getInterfaces(); for(int i=0;i<faces.length;i++){ printInfo(faces[i]); } Class cy=class1.getSuperclass(); Object cObject=null; try{ cObject=cy.newInstance(); }catch (Exception e) { // TODO: handle exception } printInfo(cObject.getClass()); } static void printInfo(Class cc){ System.out.println("Class name:"+cc.getName()+" is interface? "+cc.isInterface()); } }
以上是Java怎麼在運行期間鑑定資料類型的詳細內容。更多資訊請關注PHP中文網其他相關文章!