1,如何通过反射获取无参方法
- /****
- * 我通过反射获取的
- * @return
- */
- public JTextArea getTextArea(){
- Class clazz=MainView.class;
- Object obj=null;
- Method m;
- try {
- m = clazz.getDeclaredMethod("getTextArea", new Class[]{});
- m.setAccessible(true);
- obj=m.invoke(this, null);
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
- return (JTextArea)obj;
- }
注意:
下图是错误的:
2,如何通过反射获取有参方法
- /****
- * 我通过反射获取的
- * @return
- */
- public void formatJson(){
- Class clazz=MainView.class;
- Object obj=null;
- Method m;
- try {
- m = clazz.getDeclaredMethod("formatJson", new Class[]{String.class,boolean.class});
- m.setAccessible(true);
- obj=m.invoke(this, null);
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (SecurityException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
- }
时间: 2025-01-31 01:17:38