[英]Can't Access Protected Method of Instantiated Class
I am trying to access this protected class: protected boolean canDraw()
, and get its value placed into a variable. 我正在尝试访问此受保护的类: protected boolean canDraw()
,并将其值放入变量中。 Two ways I'm trying to access it are not working: 我尝试访问它的两种方法不起作用:
<%@ page import="com.day.cq.wcm.foundation.Image" %>
<%@include file="/apps/tju/global.jsp"%>
<% //.....
Image thisImage = new Image(resource); %>
boolean foo = thisImage.canDraw();
throws The method canDraw() from the type Image is not visible 抛出不可见的Image类型的canDraw()方法
and 和
boolean foo = super.canDraw();
throws The method canDraw() is undefined for the type HttpJspBase 抛出HttpJspBase类型的canDraw()方法未定义
Full javadoc of the class being used can be found here: http://dev.day.com/docs/en/cq/5-3/javadoc/com/day/cq/wcm/foundation/Image.html 可以在以下位置找到所使用类的完整javadoc: http : //dev.day.com/docs/en/cq/5-3/javadoc/com/day/cq/wcm/foundation/Image.html
The method is protected. 该方法受到保护。 Therefore, you cannot access it from outside of the package and the classes which inherit from the class. 因此,您不能从包以及从该类继承的类的外部访问它。
You are trying to access a protected method from a JSP page. 您正在尝试从JSP页面访问受保护的方法。 The JSP page is not a sub-class of Image and therefore cannot access the method. JSP页面不是Image的子类,因此无法访问该方法。
If there is not a better way to do what you're trying to do, subclass Image and make a public accessor for the attribute you're trying to access. 如果没有更好的方法来执行您要执行的操作,请对Image进行子类化,并为要尝试访问的属性提供公共访问器。
Well, it is protected, and you are trying to access it from a Servlet
subclass (JSPs are compiled into Servlets). 好吧,它受到保护,您正在尝试从Servlet
子类访问它(JSP被编译为Servlet)。 You can not do that, by the java specification. 根据Java规范,您不能这样做。
Make it public (if you have the source code), or extend the original class into a class that has a public method that provides the same data. 将其公开(如果您有源代码),或者将原始类扩展为具有提供相同数据的公共方法的类。 Alternatively (not recommended), use reflection to change its accessibility. 或者(不建议),使用反射更改其可访问性。
As mentioned in the other answers you would have to extend Image, override canDraw and make the overridden method's visibility public. 如其他答案中所述,您将必须扩展Image,覆盖canDraw并使覆盖的方法的可见性公开。
What do you intend to do after checking canDraw()? 检查canDraw()之后,您打算做什么? I imagine it is protected for a reason. 我想它受到保护是有原因的。 This is speculative but if all you are doing is checking canDraw() and then drawing if it returns true, you can actually just invoke draw() directly. 这是推测性的,但是如果您要做的只是检查canDraw(),然后绘制是否返回true,则实际上您可以直接调用draw()。 The JavaDoc states it internally checks canDraw(): JavaDoc声明它在内部检查canDraw():
http://dev.day.com/docs/en/cq/current/javadoc/com/day/cq/commons/ImageResource.html#draw(java.io.Writer) http://dev.day.com/docs/en/cq/current/javadoc/com/day/cq/commons/ImageResource.html#draw(java.io.Writer)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.