未知类名时Java对象动态转换及反射调用方法的可行性问询
原代码
private Object getInstance(Appl inNdOut) { Object cl = null; // I have to check for 4 instances and do casting if (null != inNdOut) { cl = (InAppl) inNdOut;// casting done } else { cl = null; } return cl; } public void dta(Appl inNdOut) { if (null != inNdOut) { Object something = getInstance(inNdOut);//inNdOut Object String theType = String.valueOf(something.getClass().getCanonicalName()); //class name to which cast to be done obtained in above Class<?> theClass = Class.forName(theType);// the object of that class //Object newObj = Class.forName(classname).cast(obj);//usual scenario //my requirement GeneralApp app = (GeneralApp) newObj //this step is common step after casting, so im trying to reuse it } }
需求与问题
因存在多场景类型转换需求且旧代码不可修改,希望通过获取类名动态转换对象,以复用后续统一逻辑,现提出两个问题:
- 上述场景能否通过代码实现?
- 能否通过代码中的
Class<?>对象调用对应类的方法?
问题1解答
可以实现,只需调整核心逻辑:
- 先补全
newObj的定义:用theClass.cast(something)完成动态类型转换,这是反射方式下的类型转换操作。 - 要确保所有需要转换的目标类都继承自
GeneralApp,否则(GeneralApp) newObj会抛出ClassCastException。 - 调整后的核心代码片段:
// 完成动态类型转换 Object newObj = theClass.cast(something); // 复用统一逻辑 GeneralApp app = (GeneralApp) newObj; // 这里可以编写针对GeneralApp的通用处理代码
旧的getInstance方法无需修改,动态转换部分会基于它返回的对象实际类型自动适配,覆盖多场景需求。
问题2解答
可以通过Class<?>对象调用对应类的方法,用Java反射实现,常见场景如下:
- 调用无参公共方法
// 假设目标类有一个无参的doSomething方法 try { Method method = theClass.getMethod("doSomething"); method.invoke(newObj); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { // 处理异常 e.printStackTrace(); }
- 调用带参数的公共方法
// 假设目标类有一个接收String参数的doSomething方法 try { Method method = theClass.getMethod("doSomething", String.class); method.invoke(newObj, "test"); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); }
如果要调用私有方法,需改用getDeclaredMethod,并调用method.setAccessible(true)解除访问限制。
内容的提问来源于stack exchange,提问作者Specter
相关产品推荐
相关产品推荐

