Static initializer not invoked
Why is the static initializer of B (in the example below) is not invoked?
public class A {
public static void m1() {
System.out.println("static m1 in A");
public class B extends A{
static {
System.out.println("static init B");
public static void m2() {
System.out.println("static m2 in A");
public class Main {
public static void main(String[] args) {
B.m1();
Surprisingly the console output is just 'static m1 in A'.
Class B doesn't have a static method named m1(). But its superclass does, so it's that method that is called. (Static methods are not inherited.) To call a method of class A, it's only necessary to load class A.
Similar Messages
-
JSP behavior - static initializer and jspInit
In a recent discussion, the concept of using a static intializer in a JSP came up. The situtation was that someone had a series of Strings used in a single JSP and they wanted to #1, define these strings in the JSP itself (vs in web.xml or a resource file, which while preferable, was not really an item of discussion) and #2 wanted indexed access to the Strings (such as via a Map).
My thought was to declare the Map variable as static final in the JSP and then initialize it in a static initializer block with Map.put operations. Both the declaration of the Map and the static initializer block would be declared in a <%! %> declaration tag block. (The thought behind the static initialization - vs overriding jspInit - being that if multiple instances of the JSP were to be created, we wouldn't want to keep put'ing values into the Map for each new instance of the JSP.)
I built the following test scenario:
<<untitled3.jsp source>>
<%@ page import="java.util.*" %>
<%!
static final Map m = new HashMap();
static int staticCount = 0;
static int jspInitCount = 0;
static {
System.out.println("static initializer called");
staticCount++;
m.put("staticCount"+staticCount, "static# " + staticCount);
public void jspInit() {
super.jspInit();
jspInitCount++;
m.put("jspInitCount"+jspInitCount, "jspInit# " + jspInitCount);
System.out.println("overriden jspInit called:" + this);
%>
Map values:<br>
<%
Collection values = m.values();
Iterator i = values.iterator();
while (i.hasNext()) {
out.println(i.next().toString() + "<br>");
%>
Test
<<end of untitled3.jsp source>>
with the following web.xml entries:
<servlet>
<servlet-name>JSPServlet1</servlet-name>
<jsp-file>untitled3.jsp</jsp-file>
</servlet>
<servlet>
<servlet-name>JSPServlet2</servlet-name>
<jsp-file>untitled3.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>JSPServlet1</servlet-name>
<url-pattern>/jsp1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>JSPServlet1</servlet-name>
<url-pattern>/jsp2</url-pattern>
</servlet-mapping>
I open a browser and request untitled3.jsp, I get the following output in the browser:
Map values:
static# 1
jspInit# 1
Test
with the following output to my JDeveloper (9.0.3.1) log window:
static initializer called
overriden jspInit called:_untitled3@61
I then request /jsp1 and get the following output in the browser:
Map values:
static# 1
jspInit# 2
jspInit# 1
Test
with the following output to my log window:
overriden jspInit called:_untitled3@63
Subsequent calls to /jsp1, /jsp2 or untitled3.jsp result in that same last output in the browser and no further output in the log window (ie, no further calls to the static initializer or jspInit method)
So, it appears that jspInit is being called once for the unmapped JSP request and one more time, the first time one of the web.xml-mapped JSP instances is requested. (I'd have thought that it would be called once for the /jsp1 request and once for the /jsp2 request...), but the static initializer is being called only once as expected.
Is this the correct behavior for the jspInit method? (ie, being called once for the unmapped request and once for the first mapped request?)
Also, if OC4J is used in a clustered/balanced configuration, is it possible that I'd end up with additional instances of my JSP in one or more JVMs?
Thanks!
Jim StollYou could scope such info to the application scope - some info is provided here: http://java.sun.com/products/jsp/tags/11/syntaxref11.fm14.html
"application - You can use the Bean from any JSP page in the same application as the JSP page that created the Bean. The Bean exists across an entire JSP application, and any page in the application can use the Bean." -
Hi,
I have been hunting down a NullPointerException for half a day to come to
the following conclusion.
My constructor calls a method which uses static variables. Since an intance
of my class is created in the static block when the class is loaded, those
statics are probably not fully initialized yet and the constructor called
from the static block has those null pointer problems.
I've considered moving the initialization of the static variables from the
declaration to the static block. But your code is inserted BEFORE any other
code. Therefore not solving my problem.
Two questions:
1) what would be a solution to my problem? How can I make sure my static
variables are initialized before the enhancer generated code in the static
block calls my constructor? Short of decompiling, changing the code and
recompiling.
2) Why is the enhancing code inserted at the beginning of the static block
and not at the end? The enhancements would be more transparent that way if
the static variables are initialized in the static block.
Thanks,
EricHi Eric,
JDO calls the no-args constructor. Your application should regard this constructor as belonging
primarily to JDO. For example, you would not want to initialize persistent fields to nondefault
values since that effort is wasted by JDO's later initilization to persistent values. Typically all
you want to initialize in the no-args constructor are the transactional and unmanaged fields. This
rule means that you need initialization after construction if your application uses the no-args
constructor and wants persistent fields initialized. On the other hand, if your application really
uses constructors with arguments, and you're initializing persistent fields in the no-args
constructor either unintentionally through field initializers or intentionally as a matter of
consistency, you will find treating the no-args constructor differently helpful.
On the other hand, if Kodo puts its static initializer code first as you report, then it is a bug.
Spec Section 20.16: "The generated static initialization code is placed after any user-defined
static initialization code."
David Ezzio
Eric Borremans wrote:
>
Hi,
I have been hunting down a NullPointerException for half a day to come to
the following conclusion.
My constructor calls a method which uses static variables. Since an intance
of my class is created in the static block when the class is loaded, those
statics are probably not fully initialized yet and the constructor called
from the static block has those null pointer problems.
I've considered moving the initialization of the static variables from the
declaration to the static block. But your code is inserted BEFORE any other
code. Therefore not solving my problem.
Two questions:
1) what would be a solution to my problem? How can I make sure my static
variables are initialized before the enhancer generated code in the static
block calls my constructor? Short of decompiling, changing the code and
recompiling.
2) Why is the enhancing code inserted at the beginning of the static block
and not at the end? The enhancements would be more transparent that way if
the static variables are initialized in the static block.
Thanks,
Eric -
How to reference a static variable before the static initializer runs
I'm anything but new to Java. Nevertheless, one discovers something new ever' once n a while. (At least I think so; correct me if I'm wrong in this.)
I've long thought it impossible to reference a static variable on a class without the class' static initializer running first. But I seem to have discovered a way:
public class Foo {
public static final SumClass fooVar; // by default initialized to null
static {
fooVar = new SumClass();
public class Bar {
public static final SumClass barVar;
static {
barVar = Foo.fooVar; // <<<--- set to null !
}Warning: Speculation ahead.
Normally the initial reference to Foo would cause Foo's class object to instantiate, initializing Foo's static variables, then running static{}. But apparently a static initializer cannot be triggered from within another static initializer. Can anyone confirm?
How to fix/avoid: Obviously, one could avoid use of the static initializer. The illustration doesn't call for it.
public class Foo {
public static final SumClass fooVar = new SumClass(); // either this ..
public class Bar {
public static final SumClass barVar = Foo.fooVar; // .. or this would prevent the problem
}But there are times when you need to use it.
So what's an elegant way to avoid the problem?DMF. wrote:
jschell wrote:
But there are times when you need to use it. I seriously doubt that.
I would suppose that if one did "need" to use it it would only be once in ones entire professional career.Try an initializer that requires several statements. Josh Bloch illustrates one in an early chapter of Effective Java, IIRC.
Another classic usage is for Singletons. You can make one look like a Monostate and avoid the annoying instance() invocation. Sure, it's not the only way, but it's a good one.
What? You only encounter those once in a career? We must have very different careers. ;)
So what's an elegant way to avoid the problem? Redesign. Not because it is elegant but rather to correct the error in the design.<pff> You have no idea what my design looks like; I just drew you a couple of stick figures.If it's dependent on such things as when a static initializer runs, it's poor. That's avoidable. Mentioning a case where such a dependency is used, that's irrelevant. It can be avoided. I know this is the point where you come up with a series of unfortunate coincidences that somehow dictate that you must use such a thing, but the very fact that you're pondering the problem with the design is a design problem. By definition.
Besides, since what I was supposing to be a problem wasn't a problem, your "solution" isn't a solution. Is it?Well, you did ask the exact question "So what's an elegant way to avoid the problem?". If you didn't want it answered, you should have said so. I'm wondering if there could be any answer to that question that wouldn't cause you to respond in such a snippy manner. Your design is supposedly problematic, as evidenced by your question. I fail to see why the answer "re-design" is unacceptable. Maybe "change the way the Java runtime initializes classes" would have been better?
This thread is bizarre. Why ask a question to which the only sane answer, you have already ruled out? -
Hello, i have a little discussion with a colleage of mine about the use of statics.
say we have a class (sqlManager) which is used to do all the sql work including the db connection.
would it be wise to make this class static. in my opinion no. perhaps make it a singleton, but not static.
My colleage thinks otherwise, make it static i do not need an object of it. it makes it easier to code and smaller.. perhaps this is true, i personally find it ugly. any suggestions.
MaqishI think if in the constructor method there are
important things to be executed, then the singleton
pattern will be better. Otherwise, the static
solution is better.There's always a static initializer (static { .. }) for static classes that have the same basic role for static content as constructors do for instance content. Not playing favorites, just pointing it out for any future readers.
If you are sure that the class has features that make
this class immutable, that is, probably it never
will be necessary to inherit the class because of its
characteristics, then you may declare its methods as
final and static.Inheritability is definitely a major factor.
This doubt is only about the architecture of the
application, that is, about its features, that must
be analized to decide what kind of class has to be
developed.As mentioned, I think a good general rule is that if you need singleton behavior, use a singleton. If you just need some utility methods, use static methods. -
Custom button with action listener - will not invoke action listener
Hi
For whatever reason, I cannot find a concise example of a simple custom component that can invoke an action listener. The tutorials I've read so far either ignore this fundamental topic or only make the slightest make reference to it.
The best I have come up with - in terms of a simple prototype is below... but, the action listener is never invoked.... Can someone tell me what I am missing (full code below). Hopefully, what is missing or incorrect will be obvious to you JSF experts out there.
Thanks for any help!!
-f
tld
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>0.01</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>jsfcustomcomponent</short-name>
<uri>http://jsfcustomcomponent/</uri>
<description><![CDATA[jsf custom component tags]]> </description>
<tag>
<name>specialBtnTag</name>
<tag-class>jsfcustomcomponent.SpecialBtnTag</tag-class>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description><![CDATA[button value]]></description>
</attribute>
<attribute>
<name>actionListener</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description><![CDATA[action listener]]> </description>
</attribute>
</tag>
</taglib>
SpecialBtnComponent
package jsfcustomcomponent;
import javax.faces.component.*;
import javax.faces.context.*;
import javax.faces.el.*;
import javax.faces.event.*;
public class SpecialBtnComponent
extends UIComponentBase implements ActionSource
public static final String COMPONENT_TYPE = "SpecialBtnComponent";
public static final String RENDERER_TYPE = "SpecialBtnRenderer";
public String getFamily()
return COMPONENT_TYPE;
public SpecialBtnComponent()
super();
setRendererType(SpecialBtnComponent.RENDERER_TYPE);
private String value;
public void setValue(String value, FacesContext facesContext)
this.value = value;
public String getValue()
if (null != value)
return value;
ValueBinding _vb = getValueBinding("value");
if (_vb != null)
return (String) _vb.getValue(getFacesContext());
else
return null;
private MethodBinding action = null;
public MethodBinding getAction()
return action;
public void setAction(MethodBinding methodBinding)
this.action = action;
private MethodBinding actionListener = null;
public MethodBinding getActionListener()
return (this.actionListener);
public void setActionListener(MethodBinding methodBinding)
this.actionListener = actionListener;
public boolean isImmediate()
return false;
public void setImmediate(boolean _boolean)
//this.immediate = immediate;
public void addActionListener(ActionListener actionListener)
addFacesListener(actionListener);
public ActionListener[] getActionListeners()
return (ActionListener[]) getFacesListeners(ActionListener.class);
public void removeActionListener(ActionListener actionListener)
removeFacesListener(actionListener);
public Object saveState(FacesContext context)
Object values[] = new Object[5];
values[0] = super.saveState(context);
values[1] = value;
values[2] = saveAttachedState(context, action);
values[3] = saveAttachedState(context, actionListener);
return ( (Object) (values));
public void restoreState(FacesContext context, Object state)
Object values[] = (Object[]) state;
super.restoreState(context, values[0]);
value = (String) values[1];
action = (MethodBinding) restoreAttachedState(context, values[2]);
actionListener = (MethodBinding) restoreAttachedState(context, values[3]);
public void broadcast(FacesEvent event) throws AbortProcessingException
super.broadcast(event);
if (event instanceof ActionEvent)
FacesContext context = getFacesContext();
MethodBinding mb = getActionListener();
if (mb != null)
mb.invoke(context, new Object[]
{event});
ActionListener listener = context.getApplication().getActionListener();
if (listener != null)
listener.processAction( (ActionEvent) event);
public void queueEvent(FacesEvent e)
if (e instanceof ActionEvent)
if (isImmediate())
e.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
else
e.setPhaseId(PhaseId.INVOKE_APPLICATION);
super.queueEvent(e);
SpecialBtnRenderer
package jsfcustomcomponent;
import java.util.*;
import javax.faces.component.*;
import javax.faces.context.*;
import javax.faces.event.*;
import javax.faces.render.*;
public class SpecialBtnRenderer
extends Renderer
String value;
public SpecialBtnRenderer()
public void decode(FacesContext context, UIComponent component)
Map requestMap = context.getExternalContext().getRequestParameterMap();
String clientId = component.getClientId(context);
SpecialBtnComponent specialBtnComponent = (SpecialBtnComponent) component;
String value = (String) requestMap.get(clientId);
if (null != value)
specialBtnComponent.setValue(value, context);
ActionEvent actionEvent = new ActionEvent(specialBtnComponent);
specialBtnComponent.queueEvent(actionEvent);
public void encodeEnd(FacesContext context, UIComponent component) throws java.io.IOException
SpecialBtnComponent specialBtnComponent = (SpecialBtnComponent) component;
ResponseWriter writer = context.getResponseWriter();
String clientId = component.getClientId(context);
value = (String) component.getAttributes().get("value");
if (value == null)
value = "defaultValue";
buildSpecialBtn(writer, value, clientId, specialBtnComponent);
private void buildSpecialBtn(ResponseWriter writer, String value, String clientId, SpecialBtnComponent component) throws java.io.IOException
writer.startElement("table", component);
writer.startElement("tbody", component);
writer.startElement("tr", component);
writer.startElement("td", component);
value = String.valueOf(value);
writer.startElement("input", component);
writer.writeAttribute("type", "submit", null);
writer.writeAttribute("name", clientId, "clientId");
writer.writeAttribute("value", value, null);
writer.endElement("input");
writer.endElement("td");
writer.endElement("tr");
writer.endElement("tbody");
writer.endElement("table");
SpecialBtnTag
package jsfcustomcomponent;
import javax.faces.component.*;
import javax.faces.el.*;
import javax.faces.webapp.*;
import com.sun.faces.util.*;
public class SpecialBtnTag
extends UIComponentTag
public String value = null;
public String actionListener = null;
public String getComponentType()
return SpecialBtnComponent.COMPONENT_TYPE;
public String getRendererType()
return SpecialBtnComponent.RENDERER_TYPE;
protected void setProperties(UIComponent component)
super.setProperties(component);
if (! (component instanceof SpecialBtnComponent))
throw new IllegalStateException("Component " + component.toString() +
" not expected type. Expected: jsfcustomcomponent.SpecialBtnComponent. Perhaps you�re missing a tag?");
SpecialBtnComponent specialBtnComponent = (SpecialBtnComponent) component;
if (value != null)
if (isValueReference(value))
ValueBinding vb = Util.getValueBinding(value);
specialBtnComponent.setValueBinding("value", vb);
else
throw new IllegalStateException("The value for �value� must be a ValueBinding.");
if (actionListener != null)
if (isValueReference(actionListener))
ValueBinding vb = Util.getValueBinding(actionListener);
specialBtnComponent.setValueBinding("actionListener", vb);
else
throw new IllegalStateException("The value for �actionListener� must be a ValueBinding.");
public void release()
super.release();
value = null;
actionListener = null;
public void setValue(String value)
this.value = value;
public String getValue()
return this.value;
public void setActionListener(String actionListener)
this.actionListener = actionListener;
public String getActionListener()
return this.actionListener;
jsp1.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://jsfcustomcomponent/" prefix="j"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<link rel="stylesheet" type="text/css" href="./stylesheet.css" title="Style">
</head>
<body>
<f:view>
<h:form id="form01">
<h:outputText value="test special button with action listener"/>
<j:specialBtnTag value="#{specialBtnBacking.specialBtnValue}" actionListener="#{specialBtnBacking.specialBtnActionListener}"/>
<h:messages/>
<h:outputText value="#{specialBtnBacking.outcome}"/>
</h:form>
</f:view>
</body>
</html>
SpecialBtnBacking
package specialbtn;
import javax.faces.context.*;
import javax.faces.event.*;
public class SpecialBtnBacking
private FacesContext context;
public SpecialBtnBacking()
this.setSpecialBtnValue("Special Button with action listener");
private String specialBtnValue;
public String getSpecialBtnValue()
return this.specialBtnValue;
public void setSpecialBtnValue(String specialBtnValue)
this.specialBtnValue = specialBtnValue;
private String outcome="actionlistener NOT invoked: click specialBtn above to test";
public String getOutcome()
return outcome;
public void setOutcome(String outcome)
this.outcome = outcome;
public void specialBtnActionListener(ActionEvent evt)
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Jsp1Backing/specialBtnActionListener()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
this.outcome="***action listener invoked!!!***";
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN" "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config>
<managed-bean>
<managed-bean-name>specialBtnBacking</managed-bean-name>
<managed-bean-class>specialbtn.SpecialBtnBacking</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<component>
<component-type>SpecialBtnComponent</component-type>
<component-class>jsfcustomcomponent.SpecialBtnComponent</component-class>
<component-extension>
<renderer-type>SpecialBtnRenderer</renderer-type>
</component-extension>
</component>
<render-kit>
<renderer>
<component-family>SpecialBtnComponent</component-family>
<renderer-type>SpecialBtnRenderer</renderer-type>
<renderer-class>jsfcustomcomponent.SpecialBtnRenderer</renderer-class>
</renderer>
</render-kit>
</faces-config>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<display-name>pagerWEB</display-name>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<jsp-config>
<taglib>
<taglib-uri>http://jsfcustomcomponent/</taglib-uri>
<taglib-location>/WEB-INF/jsfcustomcomponent.tld</taglib-location>
</taglib>
</jsp-config>
<servlet>
<description>Added by JBuilder to compile JSPs with debug info</description>
<servlet-name>debugjsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<init-param>
<param-name>classdebuginfo</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>debugjsp</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
</web-app>got it working....
The changes were:
in "SpecialBtnRenderer"...
--new--
mb.invoke(context, new Object[1]);
--old--
mb.invoke(context, new Object[0]);
in "SpecialBtnTag"...
--new--
import javax.faces.event.ActionEvent;
--new--
MethodBinding mb = FacesContext.getCurrentInstance().getApplication().createMethodBinding(specialBtnListener, new Class[]{ActionEvent.class});
--old--
MethodBinding mb = FacesContext.getCurrentInstance().getApplication().createMethodBinding(specialBtnListener, null);
-Below is the entire application, again -- for those (like myself) who need concrete examples...
I hope this helps someone else! --f
jsp1.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@taglib uri="http://jsfcustomcomponent/" prefix="j"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<link rel="stylesheet" type="text/css" href="./stylesheet.css" title="Style">
</head>
<body>
<f:view>
<h:messages/>
<h:form id="form01">
<h:outputText value="test special button with action listener"/>
<j:specialBtnTag value="#{specialBtnBacking.specialBtnValue}" specialBtnListener="#{specialBtnBacking.specialBtnActionListener}"/>
<h:outputText value="#{specialBtnBacking.outcome}"/>
</h:form>
</f:view>
</body>
</html>
SpecialBtnBacking
package specialbtn;
import javax.faces.context.*;
import javax.faces.event.*;
public class SpecialBtnBacking
private FacesContext context;
public SpecialBtnBacking()
this.setSpecialBtnValue("Special Button with action listener");
private String specialBtnValue;
public String getSpecialBtnValue()
return this.specialBtnValue;
public void setSpecialBtnValue(String specialBtnValue)
this.specialBtnValue = specialBtnValue;
private String outcome = "actionlistener NOT invoked: click specialBtn above to test";
public String getOutcome()
return outcome;
public void setOutcome(String outcome)
this.outcome = outcome;
public void specialBtnActionListener(ActionEvent evt)
System.out.println("\n\n");
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Jsp1Backing/specialBtnActionListener()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Jsp1Backing/specialBtnActionListener()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Jsp1Backing/specialBtnActionListener()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Jsp1Backing/specialBtnActionListener()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Jsp1Backing/specialBtnActionListener()!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n");
this.outcome = "***action listener invoked!!!***";
jsfcustomcomponent.tld
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>0.01</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>jsfcustomcomponent</short-name>
<uri>http://jsfcustomcomponent/</uri>
<description><![CDATA[jsf custom component tags]]> </description>
<tag>
<name>specialBtnTag</name>
<tag-class>jsfcustomcomponent.SpecialBtnTag</tag-class>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description><![CDATA[button value]]></description>
</attribute>
<attribute>
<name>specialBtnListener</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description><![CDATA[action listener]]> </description>
</attribute>
</tag>
</taglib>
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN" "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config>
<managed-bean>
<managed-bean-name>specialBtnBacking</managed-bean-name>
<managed-bean-class>specialbtn.SpecialBtnBacking</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<component>
<component-type>SpecialBtnComponent</component-type>
<component-class>jsfcustomcomponent.SpecialBtnComponent</component-class>
<component-extension>
<renderer-type>SpecialBtnRenderer</renderer-type>
</component-extension>
</component>
<render-kit>
<renderer>
<component-family>SpecialBtnComponent</component-family>
<renderer-type>SpecialBtnRenderer</renderer-type>
<renderer-class>jsfcustomcomponent.SpecialBtnRenderer</renderer-class>
</renderer>
</render-kit>
</faces-config>
SpecialBtnComponent.java
package jsfcustomcomponent;
import javax.faces.component.*;
import javax.faces.context.*;
import javax.faces.el.*;
import javax.faces.event.*;
public class SpecialBtnComponent
extends UIComponentBase implements ActionSource
public static final String COMPONENT_TYPE = "SpecialBtnComponent";
public static final String RENDERER_TYPE = "SpecialBtnRenderer";
public String getFamily()
return COMPONENT_TYPE;
public SpecialBtnComponent()
super();
setRendererType(SpecialBtnComponent.RENDERER_TYPE);
private String value;
public void setValue(String value, FacesContext facesContext)
this.value = value;
public String getValue()
if (null != this.value)
return this.value;
ValueBinding _vb = getValueBinding("value");
if (_vb != null)
return (String) _vb.getValue(getFacesContext());
else
return null;
private MethodBinding specialBtnListener = null;
public MethodBinding getActionListener()
return (this.specialBtnListener);
public void setActionListener(MethodBinding actionListener)
this.specialBtnListener = actionListener;
public Object saveState(FacesContext context)
Object values[] = new Object[3];
values[0] = super.saveState(context);
values[1] = saveAttachedState(context, this.specialBtnListener);
values[2] = this.value;
return (values);
public void restoreState(FacesContext context, Object state)
Object values[] = (Object[]) state;
super.restoreState(context, values[0]);
this.specialBtnListener = (MethodBinding) restoreAttachedState(context, values[1]);
this.value = (String) restoreAttachedState(context, values[2]);
public void broadcast(FacesEvent event) throws AbortProcessingException
super.broadcast(event);
if (event instanceof ActionEvent)
FacesContext context = getFacesContext();
MethodBinding mb = this.getActionListener();
if (mb != null)
try
mb.invoke(context, new Object[]
{event});
catch (EvaluationException ex)
System.out.println("SpecialBtnComponent/broadcast(FacesEvent event)...EvaluationException encountered - ex.getMessage()=" + ex.getMessage());
ex.printStackTrace();
ActionListener actionListener = context.getApplication().getActionListener();
if (actionListener != null)
actionListener.processAction( (ActionEvent) event);
public void queueEvent(FacesEvent e)
if (e instanceof ActionEvent)
e.setPhaseId(PhaseId.INVOKE_APPLICATION);
super.queueEvent(e);
public MethodBinding getAction()
return null;
public void setAction(MethodBinding methodBinding)
public boolean isImmediate()
return false;
public void setImmediate(boolean _boolean)
public void addActionListener(ActionListener actionListener)
addFacesListener(actionListener);
public ActionListener[] getActionListeners()
return (ActionListener[]) getFacesListeners(ActionListener.class);
public void removeActionListener(ActionListener actionListener)
removeFacesListener(actionListener);
SpecialBtnTag.java
package jsfcustomcomponent;
import javax.faces.component.*;
import javax.faces.el.*;
import javax.faces.webapp.*;
import com.sun.faces.util.*;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
public class SpecialBtnTag
extends UIComponentTag
public String value = null;
public String specialBtnListener = null;
private SpecialBtnComponent specialBtnComponent;
public SpecialBtnTag()
super();
public String getComponentType()
return SpecialBtnComponent.COMPONENT_TYPE;
public String getRendererType()
return SpecialBtnComponent.RENDERER_TYPE;
protected void setProperties(UIComponent component)
super.setProperties(component);
if (! (component instanceof SpecialBtnComponent))
throw new IllegalStateException("Component " + component.toString() +
" not expected type. Expected: jsfcustomcomponent.SpecialBtnComponent. Perhaps you�re missing a tag?");
specialBtnComponent = (SpecialBtnComponent) component;
if (value != null)
if (isValueReference(value))
ValueBinding vb = Util.getValueBinding(value);
specialBtnComponent.setValueBinding("value", vb);
else
throw new IllegalStateException("The value for �value� must be a ValueBinding.");
if (specialBtnListener != null)
if (isValueReference(specialBtnListener))
MethodBinding mb = FacesContext.getCurrentInstance().getApplication().createMethodBinding(specialBtnListener, new Class[]{ActionEvent.class});
( (SpecialBtnComponent) component).setActionListener(mb);
else
MethodBinding mb = Util.createConstantMethodBinding(specialBtnListener);
( (SpecialBtnComponent) component).setActionListener(mb);
public void release()
super.release();
value = null;
specialBtnListener = null;
public void setValue(String value)
this.value = value;
public String getValue()
return this.value;
public void setSpecialBtnListener(String specialBtnListener)
this.specialBtnListener = specialBtnListener;
public String getSpecialBtnListener()
return this.specialBtnListener;
SpecialBtnRenderer
package jsfcustomcomponent;
import java.util.*;
import javax.faces.component.*;
import javax.faces.context.*;
import javax.faces.event.*;
import javax.faces.render.*;
import javax.faces.el.MethodBinding;
import javax.faces.el.*;
public class SpecialBtnRenderer
extends Renderer
String value;
public SpecialBtnRenderer()
super();
public void decode(FacesContext context, UIComponent component)
try
Map requestMap = context.getExternalContext().getRequestParameterMap();
String clientId = component.getClientId(context);
SpecialBtnComponent specialBtnComponent = (SpecialBtnComponent) component;
String value = (String) requestMap.get(clientId);
if (null != value)
specialBtnComponent.setValue(value, context);
MethodBinding mb = specialBtnComponent.getActionListener();
if (mb != null)
System.out.println("SpecialBtnRenderer/decode...mb.getExpressionString()=" + mb.getExpressionString());
//mb.invoke(context, new Object[0]);
mb.invoke(context, new Object[1]);
ActionEvent actionEvent = new ActionEvent(specialBtnComponent);
specialBtnComponent.queueEvent(actionEvent);
catch (EvaluationException ex)
ex.printStackTrace();
public void encodeEnd(FacesContext context, UIComponent component) throws java.io.IOException
SpecialBtnComponent specialBtnComponent = (SpecialBtnComponent) component;
ResponseWriter writer = context.getResponseWriter();
String clientId = component.getClientId(context);
value = (String) component.getAttributes().get("value");
if (value == null)
value = "defaultValue";
buildSpecialBtn(writer, value, clientId, specialBtnComponent);
private void buildSpecialBtn(ResponseWriter writer, String value, String clientId, SpecialBtnComponent component) throws java.io.IOException
writer.startElement("table", component);
writer.startElement("tbody", component);
writer.startElement("tr", component);
writer.startElement("td", component);
value = String.valueOf(value);
writer.startElement("input", component);
writer.writeAttribute("type", "submit", null);
writer.writeAttribute("name", clientId, "clientId");
writer.writeAttribute("value", value, null);
writer.endElement("input");
writer.endElement("td");
writer.endElement("tr");
writer.endElement("tbody");
writer.endElement("table");
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<display-name>pagerWEB</display-name>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<jsp-config>
<taglib>
<taglib-uri>http://jsfcustomcomponent/</taglib-uri>
<taglib-location>/WEB-INF/jsfcustomcomponent.tld</taglib-location>
</taglib>
</jsp-config>
</web-app> -
hi guys,
can anyone explain what might cause the following error?
i have the following classes
class BonesPlayLevel {
// execution reaches here
ObjFigure.initJointedModel();
class ObjFigure {
public static void initJointedModel() {
// execution does not reach here
initJointedModelList(myVecs);
and when i try and run i get the following error message:
java.lang.Error: Static initializer: java.lang.NullPointerException
java.land.Error
cheers
spobits ok i understand how to debug, and how the stack trace works.
i am running this in JBuilder, here is the output produced
D:\Nokia\Devices\Series_60_MIDP_Concept_SDK_Beta_0_3_1_Nokia_edition\bin\emulator.exe -classpath "E:\javaApps\MIDlets\mlj3d_exbones\classes;D:\MLJ3D\v1.0.1dev\jars\mljFrame.jar;D:\MLJ3D\v1.0.1dev\jars\mljRender.jar;" -Xdevice:Series_60_MIDP_Concept_SDK_Beta_0_3_1_Nokia_edition -Xdescriptor:"E:\javaApps\MIDlets\mlj3d_exbones\jad-temp\ExBones.jad"
java.lang.Error: Static initializer: java/lang/NullPointerException -
Instance initializer and static initializer blocks
Hi guys,
I read about the above mentioned in the JLS and also in a book before, but I still don't quite understand, what is the use of these. I sort of have a rough idea, but not exactly. I mean, what is the purpose of the instance initializer and static initializer blocks, how can it be useful? I understand I can execute pieces of code that will initialize instance and static variables accordingly, but how is it different then to using a constructor to initialize these fields? Are these pieces of code executed before any constructor is executed, or when otherwise?
Sorry for my noob, I'm learning.
PR.Static initializers are useful for initializing a class when the initialization is more complex than simply setting a single variable, or when that initialization can throw a checked exception.
public class Foo {
private static final Bar bar;
static {
try {
bar = new Bar();
bar.doSomeInitializationStuff();
catch (SomeCheckedExceptionThatBarThrows e) {
throw new ExceptionInInitializerError(e);
}Here we could not do the two-step new Bar() + doSomeInit() stuff in the line where we declare the bar variable. Additionally, assuming that one or both of those can throw a checked exception, we could not do that on the declaration line; we need the static initializer to wrap that in the appropriate unchecked exception.
This allows us to do more complex class initialization when the class is loaded than we could do with a simple variable initialization.
Instance initializers are useful if you want to perform the same steps in every constructor and don't want to have to repeat the code in each constructor. Instance initializers are executed as the first step of each constructor (or maybe it's after any super() calls, I forget). -
Exception in static initializer
Hi,
I have one class with one static variable.
I am initializing this variable in static initializer block. But while initializing, it is throwing some checked exception which I dont want to catch in block.
Static initializer block doesn't support "throws", what should be done?
Thankshm..
I think it depends on implementation.. etc
Anyways, point is not where I should catch the
exception. Point is, how can I throw the exception to
caller when I am initializing static members. I don't think this makes sense! The 'caller' has to be the class loader so unless you are using your own class loader then you don't have any real choice.
You could always wrap the exception in an un-checked exception and let the system handle it but this may just close the application anyway! -
Uncaught exception: Static initializer: java/lang/SecurityException
So i'm trying to compile some code of a small game for Doja.
The code compiles fine but when i load it in the emulator i get the following eror:
Uncaught exception java/lang/Error: Static initializer: java/lang/SecurityException.
Now i haven't seen that before. I looked into it and first i thought there must be some static initializer block in some class but there isn't.
Now i'm kinda stumped. What else can be the problem?A security exception is usually thrown when you try to use some function of the API that you're not allowed to use.
For example, if the user has not given your application permission to connect to the internet, but you try to do so.
Sometimes this error can be resolved by turning on the appropriate option in the ADF file.
Cheers,
Sam -
Initializing array elements on a static initialization block
Hello,
I have this class:
class Foo{
public static Wing[] flights = new Wing[20]; //initialize with null Wing references
static { //static initialization block - begin
for(Wing w : flights){ //for each Wing slot on the array,
w = new Wing(); //create a Wing object and refer to it
} // static init block - endThe code above creates a Wing array, and the static init block should create 20 Wing objects on the array slots, but the objects are lost when I try to use it in the main method on the same class Foo:
public static void main(String[] args){
System.out.println(flights[3].name); //will throw NullPointerException -> Array elements have not been initialized
}How is that possible? The init code for(Wing w : flights) looks like has created copies of the objects, and not just references to the same object. If I change the static init block to the "old-fashioned for loop"
for (int i=0; i < flights.length; i++){
flights[i] = new Wing();then it works.
But I think that the problem is not on the kind of for loop itself, because if I use same static initialization statement, with for (Wing w : flights) on the main method, instead of in a separate init block, the array gets populated with solid objects.
Any ideas of what I am doing wrong?
Java version: 5.0I think I got it. I am reseting the reference to point to a new Object in the heap instead of the array slot. :-P
-
Why Component do not invoke KeyListener,when it is a CellEditor in JTable?
when I edit at a cell ,the JTextField do not invoke keylilsten,why?
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.util.EventObject;
public class Test extends JFrame {
public JTable table;
public JScrollPane scrollpane;
public Test() {
JTextField editor;
this.table = new JTable(5,5);
this.scrollpane=new JScrollPane(table);
for (int i=0;i<5;i++) {
editor=new JTextField();
editor.setBackground(Color.blue);
editor.setForeground(Color.white);
editor.addKeyListener(new kl()); //addkeylistener
this.table.getColumnModel().getColumn(i).setCellEditor(new DefaultCellEditor(editor));
this.getContentPane().add(this.scrollpane);
this.scrollpane.setVisible(true);
this.setSize(300,300);
this.setVisible(true);
public static void main(String args[]){
Test test=new Test();
//KeyListener
class kl implements KeyListener {
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased...");
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed...");
public void keyTyped(KeyEvent e){
System.out.println("keytype...");
}I changed your code a bit to show you what you were doing wrong, you need to implement KeyListener:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.util.EventObject;
public class Test extends JFrame implements KeyListener {
public JTable table;
public JScrollPane scrollpane;
public Test() {
JTextField editor;
this.table = new JTable(5,5);
this.scrollpane=new JScrollPane(table);
for (int i=0;i<5;i++) {
editor=new JTextField();
editor.setBackground(Color.blue);
editor.setForeground(Color.white);
editor.addKeyListener( this ); //addkeylistener
this.table.getColumnModel().getColumn(i).setCellEditor(new DefaultCellEditor(editor));
this.getContentPane().add(this.scrollpane);
this.scrollpane.setVisible(true);
this.setSize(300,300);
this.setVisible(true);
public static void main(String args[]){
Test test=new Test();
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased...");
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed...");
public void keyTyped(KeyEvent e){
System.out.println("keytype..."); -
How to force subclass static initialization?
Interesting problem. Here's the setup:
public class Properties1 implements Properties1Keys {
private void Hashtable ht = new Hashtable();
static { ht.put(prop1Key, "Test1"); }
public static Object get(String key) { return ht.get(key); }
public static void put(String key, Object o) { ht.put(key, o); }
public interface Properties1Keys {
public final static String prop1Key = "prop1";
public class Properties2 extends Properties1 implements Properties2Keys {
static { put(prop2Key, "Test2"); }
public interface Properties2Keys {
public final static String prop2Key = "prop2";
Now, if the first thing we do is Properties2.get(Properties2.prop2Key) we will get a (null,) because no fields or methods from Properties2 have been accessed, and the static initializer is not executed.
How can we automatically force Properties2 static initialization without either declaring some dummy method to be called first or reimplementing Properties1 methods. Properties1 is extended to import it's keys. Implementing Properties1Keys is not an option because further subclasses of this will need to implement all the stuff above it. This would be the most elegant solution (I think) but it fails to initialize because of the VM spec.
Is the only solution a semi-screwy singleton?Interesting problem. Here's the setup:Unless I am reading something wrong that code makes absolutely no sense.
public class Properties1 This class has a static initializer. Static initializers are called when the class is loaded. Static initializers have nothing to do with instances of the class. Just as static methods have nothing to do with instances of a class.
The static initializer in Properties1 is calling a member variable. A variable that does not even exist in the context of a static initializer. That should be all that needs to be said on the subject.
Lets presume that ht should have been static (since everything else is static.)
When the class Properties2 is loaded one of the first things that occurs is that the parent classes are also loaded. Thus Properties1 is loaded. And likewise Properties1Keys is loaded.
When Properties1Keys is loaded, it assigns the value to prop1Key. Thus when the static initializer of Propperties1 runs, prop1Key will have a value.
Perhaps the problem lies in thinking that the values are initialized when the methods are accessed rather than when the classes are loaded?
And in actual point of fact, because the values are declared 'final' it does not matter if prop1Key is initialized or not. Because the compiler will have already optimized the variable away. Consequently the code will be doing basically the following:
static { ht.put("prop1", "Test1"); }
This is relevant if the interface Properties1Keys changes and all of the dependent classes are not rebuilt. The values will not match. -
[SOLVED] netcfg static IP not persisting across reboots in VM
I ran into an issue with netcfg static IP not persisting across reboots in a VM. I figured it out, but it took me awhile as a brand new user, so I thought I'd post it.
Setup
Using VMWare Workstation 8.0.3 build-703057 with bridged networking
Host OS: Linux Mint 14 64-bit
Guest OS: Arch Linux 2013.03.01 x86_64
Given a fresh install on the guest, setup netcfg:
cd /etc/network.d
cp examples/ethernet-static ./myprofile
nano myprofile
# customize this file. I also added NETMASK='255.255.255.0'
systemctl enable netcfg@myprofile
systemctl start netcfg@myprofile
Test the configuration. It should be successful:
ping google.com
Problem
See if the changes survive a reboot.
reboot
ping google.com
I got the error "connect: Network is unreachable".
Check the logs:
journalctl
G
I found the following netcfg failure..
[email protected]: main process exited, code=exited, status=1/FAILURE
..prior to the following device initialization:
kernel: e1000 0000:02:00.0 eth0: Intel(R) PRO/1000 Network Connection
system-udevd[117]: renamed network interface eth0 to emp2s0
Solution
It looks like netcfg is being started before the device it depends on has been initialized. Inform systemd of the
dependency so they start in the proper order:
# nano /etc/systemd/system/multi-user.target.wants/[email protected]
# Add the following to [Unit]. Remember to replace enp2s0 with your device name.
Requires=sys-subsystem-net-devices-enp2s0.device
After=sys-subsystem-net-devices-enp2s0.device
Test again:
reboot
ping google.com
This should now be successful.fukawi2 wrote:
$ man netcfg-profiles wrote:
Miscellaneous options
IPCFG
Array of arguments to pass to ip. The power of this options is
that it allows both simple and complicated routing
configurations, within the framework of netcfg.
SKIPNOCARRIER
‘yes’/‘no’. Don’t abort interface setup if no carrier is
found.
Thank you, [Solved]. -
Is static initialization of a class varaible guaranteed to occur only once?
In other words, if two threads attempt to create an instance of this class, would the static initialization of ConnectionFactory occur once?
public ConnectionSource {
private static ConnectionFactory factory = new ConnectionFactory();
I need exactly one instance of ConnectionFactory.
SAFif ConnectionSource is unloaded (because there are no references to any instances on ConnectionSource, and no reference to the Class object itself), then a different ConnectionFactory would be created when the class is reloaded. This may or may not affect your program execution.
Hackmann
Maybe you are looking for
-
Compiling Wine (32-bit) on Arch64 with multilib
Now I know multilib is not officially supported by Arch, but I need to apply a patch to Wine before compiling it in order to be able to play a game. I have installed all the lib32 files (well not all, not catalyst or glibs etc.) but I have all the ne
-
Hello all, I have a field which type is nvarchar (100). When I insert English characters to this column, it works whell. But when I insert Chinese, the limitation is more less than 100. Who can tell me why? Thanks a lot!
-
Create a Doc for Filling Out and Sending On
I'm trying to create a document for pricing quotes. The idea is that I (designer) create a document (writable) for a client to fill out, save (unwritable), and send to customers for price quotes. I've tried: creating text boxes - but when the documen
-
Oracle Universal Installer response files and platform independency
Hi all, The Oracle Universal Installer is a platform-independent system, to what extent are Oracle Universal Installer response files platform-independent? For sure it's not completely platform-independent, because path definitions aren't portable -
-
Hello, I have two db2 db with different versions (7.1 and 8.1), I can only access a db2 db with driver of it's own version. I can't put both versions in XI. How do I solve this. Regards, Sanjay