Java运行时动态加载类之Class.forName

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

需求场景:通过Class.forName加载类并创建实例。

1、接口类:

package cn.fjs;

public interface IC {
	public void action();
}

2、实例类:

package cn.fjs;

public class C implements IC{
	public void action(){
		System.out.println("Hi i am A class.");
	}
}

3、测试类:

package cn.fjs;

import java.util.Scanner;

public class demo {
	public static void main(String[] args){
		System.out.print("\nPls enter the class name:like cn.fjs.C \n");
		Scanner sc = new Scanner(System.in);
		String cname = sc.next();
		try{
			Class aClass = Class.forName(cname);
			IC ic = (IC)aClass.newInstance();			
			ic.action();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}


展开阅读全文

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