1、认识class类
1)产生了实例化对象
import java.util.Date; public class GetClassDemo1 { public static void main(String[] args) { Date date = new Date(); Class<?> cls = date.getClass(); System.out.println(cls); } }
2)未产生实例化对象
import java.util.Date; public class GetClassDemo1 { public static void main(String[] args) { Class<?> cls = Date.class; System.out.println(cls); } }
3)调用class类的方法,不用import语句导入明确的类,采用forname方法描述类名称。
public class GetClassDemo1 { public static void main(String[] args) throws ClassNotFoundException { Class<?> cls = Class.forName("java.util.Date"); System.out.println(cls); } }
运行结果相同:
class java.util.Date
2、对象实例化
class BookObject{ public BookObject(){ System.out.println("***无参构造***"); } @Override public String toString() { return "这是一个例子"; } } public class GetClassDemo1 { public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException { Class<?> cls = Class.forName("com.hengqin.test1.BookObject"); Object obj = cls.newInstance(); System.out.println(obj); } }
interface IFruit{ public void eat(); } class Appl implements IFruit{ @Override public void eat() { System.out.println("***吃苹果***"); } } class Factory2{ public static IFruit getInstance(String classname){ IFruit f = null; try { f = (IFruit) Class.forName(classname).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return f; } } public class FactorRegexDemo1 { public static void main(String[] args) { IFruit f = Factory2.getInstance("com.hengqin.test1.Appl"); f.eat(); } }
3、使用反射调用构造(明确调用类中的有参构造)
import java.lang.reflect.Constructor; public class GetConstructDemo1 { public static void main(String[] args) throws Exception { Class<?> cls = Class.forName("com.hengqin.test1.Book"); Constructor<?> con = cls.getConstructor(String.class,double.class); Object obj = con.newInstance("java",89.7); System.out.println(obj); } }
4、反射调用方法
public class GetConstructDemo1 { public static void main(String[] args) throws Exception { String filename = "title"; Class<?> cls = Class.forName("com.hengqin.test1.Book1"); Object obj = cls.newInstance(); Method setMet = cls.getMethod("set"+initcap(filename), String.class); Method getMet = cls.getMethod("get"+initcap(filename)); setMet.invoke(obj,"java"); System.out.println(getMet.invoke(obj)); } public static String initcap(String str){ return str.substring(0,1).toUpperCase()+str.substring(1); } }