如何从孩子调用父私有方法?
public class A{ private int getC(){ return 0; } } public class B extends A{ public static void main(String args[]){ B = new B(); //here I need to invoke getC() } }
你能否告诉我是否有可能通过java中的reflection做一些事情?
class A{ private void a(){ System.out.println("private of A called"); } } class B extends A{ public void callAa(){ try { System.out.println(Arrays.toString(getClass().getSuperclass().getMethods())); Method m = getClass().getSuperclass().getDeclaredMethod("a", new Class>[]{}); m.setAccessible(true); m.invoke(this, (Object[])null); } catch (Exception e) { e.printStackTrace(); } } }
您可以使用reflection来完成,但除非有充分的理由这样做,否则您应该首先重新考虑您的设计。
下面的代码打印123,即使从外面A调用。
public static void main(String[] args) throws Exception { Method m = A.class.getDeclaredMethod("getC"); m.setAccessible(true); //bypasses the private modifier int i = (Integer) m.invoke(new A()); System.out.println("i = " + i); //prints 123 } public static class A { private int getC() { return 123; } }
你应该声明getc protected。 这正是它的用途。
至于反思:是的,这是可能的。 您必须在方法对象上调用setAccessible。 这是糟糕的风格… 😉
getDeclaredMethod只返回当前类中的私有方法而不返回inheritance的方法。 要实现它,您需要通过getSuperclass方法导航inheritance图。 这是一个执行它的代码片段
private Method getPrivateMethod(Object currentObject) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { Class> currentClass = currentObject.getClass(); Method method = null; while (currentClass != null && method == null) { try { method = currentClass.getDeclaredMethod("getC"); } catch (NoSuchMethodException nsme) { // method not present - try super class currentClass = currentClass.getSuperclass(); } } if (method != null) { method.setAccessible(true); return method; } else { throw new NoSuchMethodException(); }
}
你可以尝试这样使用reflection:
Method getCMethod = A.class.getDeclaredMethod("getC"); getCMethod.setAccessible(true); getCMethod.invoke(new A());
- 在Eclipse中增加Java堆大小 – 使用虚拟内存
- 在Java 6中,向下转换的成本有多高?
- 如何在Java中卸载已加载的类?
- 可选与null。 Java 8中Optional的目的是什么?
- Hibernate UnknownServiceException:在事务完成时请求未知服务
- 通过EL 3.0访问JSP中的静态属性或方法(JEE7; Tomcat 8)
- ClassNotFoundException启动Tomcat时的DispatcherServlet(Maven依赖项未复制到wtpwebapps)
- 如果包含元素被修改,Java HashSet包含重复项
- 我应该何时关闭在无状态会话bean中创建的JMS连接?