首页 > 代码库 > Java 反射基础

Java 反射基础

三种方式获取对象类型:

 1 package com.helen.test; 2  3 import java.util.Date; 4  5 public class Reflect { 6 public static void main(String[] args) { 7     Date date=new Date(); 8     System.out.println(date.getClass().getName()); 9     10     Class<?> clas=java.util.Date.class;11     System.out.println(clas.getName());12     13 14     try {15         Class<?> clas1 = Class.forName("java.util.Date");16         System.out.println(clas1.getName());17     } catch (ClassNotFoundException e) {18         19         e.printStackTrace();20     }21     22 }23 }

 

 

利用反射实现工厂模式

 1 package com.helen.test; 2  3 import java.util.Date; 4  5 interface Fruit { 6     public void eat(); 7 } 8  9 class Apple implements Fruit {10 11     public void eat() {12         System.out.println("helen eat 苹果!");13     }14 15 }16 17 class Orange implements Fruit {18 19     public void eat() {20         System.out.println("helen eat 橘子!");21     }22 23 }24 25 class Factory {26     public static Fruit getFruit(String className) {27         Fruit fruit = null;28         try {29             Class<?> clas = Class.forName(className);30             fruit = (Fruit) clas.newInstance();  //实例一个对象31 32         } catch (Exception e) {33 34             e.printStackTrace();35         }36         return fruit;37 38     }39 }40 41 public class Reflect_Factory {42     public static void main(String[] args) {43         Fruit fruit=Factory.getFruit("com.helen.test.Apple");44         Fruit fruit1=Factory.getFruit("com.helen.test.Orange");45         fruit.eat();46         fruit1.eat();47     }48 }

 

Java 反射基础