使用反射例項化內部類方式
阿新 • • 發佈:2019-01-07
使用反射例項化內部類方式
@SuppressWarnings("unchecked") private static Object getInstance(Class<?> clz) { Object obj = null; if (clz.isMemberClass()) { Class<?> declaredClass = clz.getDeclaringClass(); try { Constructor<Object> dc = (Constructor<Object>) clz.getDeclaredConstructor(declaredClass); dc.setAccessible(true); obj = dc.newInstance(declaredClass.newInstance()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } else { try { obj = clz.newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return obj; }