本帖最后由 郑飞 于 2014-10-25 11:53 编辑
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.lang.reflect.Method;
- public class SysinReflect {
- /**
- * 接收控制台输入的一个类名(这个类事先定义好),通过反射创建这个类的对象并调用里面的方法;
- * @throws Exception
- */
- public static void main(String[] args) throws Exception
- {
- String classname = "BeReflect";//定义用于比较类名的字符串;
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String line = null;
- System.out.println("InPut A ClassName(exit whit \"end\"):");
- while((line = br.readLine())!=null)
- {
- if(line.equals(classname))
- {
- //进行反射
- Class c = Class.forName(line);
- Method m = c.getMethod("test", null);
- m.invoke(c.newInstance(), null);
- }else if(line.equalsIgnoreCase("end"))
- {
- System.out.println("exit");
- break;
- }
- else
- System.out.println("ClassNotFound,InPut Again:");
- }
- br.close();
- }
- }
- class BeReflect
- {
- public void test()
- {
- System.out.println("i'm reflect!");
- }
- }
复制代码
|
|