Java 反射机制(反射实例化对象)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ikv1989/article/details/80237916

范例1:利用反射实例化对象

class Book {
	public Book() {
		System.out.println("*********Book类无参构造方法***********");
	}

	@Override
	public String toString() {
		return "这是一本书";
	}
}

public class Demo {
	public static void main(String[] args) throws Exception {
		Class<?> cla = Class.forName("ikvDemo.Book");
		Object obj = cla.newInstance();
		Book book = (Book) obj;
		System.out.println(book);
	}
}

===========分割线===========

范例2:修改工厂模式

interface Fruit {
	public abstract void eat();
}

class Apple implements Fruit {
	@Override
	public void eat() {
		System.out.println("吃苹果....");
	}
}

class Orange implements Fruit {
	@Override
	public void eat() {
		System.out.println("吃橙子....");
	}
}

class Factory {
	public static Fruit getInstance(String className) {
		Fruit f = null;
		try {
			f = (Fruit) Class.forName(className).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return f;
	}
}

public class Demo {
	public static void main(String[] args) {
		Fruit f = Factory.getInstance("ikvDemo.Orange");
		f.eat();
	}
}

展开阅读全文

没有更多推荐了,返回首页