我正在学习Java编程,发现了这段代码:
//load the AppTest at runtime
Class cls = Class.forName("com.mkyong.reflection.AppTest");
Object obj = cls.newInstance();
//call the printIt method
Method method = cls.getDeclaredMethod("printIt", noparams);
method.invoke(obj, null);
我的问题是:如果我不知道类类型,尝试强制转换对象而不是调用方法是否更容易(并且更快)?
为什么(以及何时)应该使用这种方法?