Categories
discuss

Java: how to initialize String[]?

Error

% javac  StringTest.java 
StringTest.java:4: variable errorSoon might not have been initialized
        errorSoon[0] = "Error, why?";

Code

public class StringTest {
        public static void main(String[] args) {
                String[] errorSoon;
                errorSoon[0] = "Error, why?";
        }
}

Answer

You need to initialize errorSoon, as indicated by the error message, you have only declared it.

String[] errorSoon;                   // <--declared statement
String[] errorSoon = new String[100]; // <--initialized statement

You need to initialize the array so it can allocate the correct memory storage for the String elements before you can start setting the index.

If you only declare the array (as you did) there is no memory allocated for the String elements, but only a reference handle to errorSoon, and will throw an error when you try to initialize a variable at any index.

As a side note, you could also initialize the String array inside braces, { } as so,

String[] errorSoon = {"Hello", "World"};

which is equivalent to

String[] errorSoon = new String[2];
errorSoon[0] = "Hello";
errorSoon[1] = "World";
Categories
discuss

Why does Java’s invokevirtual need to resolve the called method’s compile-time class?

Consider this simple Java class:

class MyClass {
  public void bar(MyClass c) {
    c.foo();
  }
}

I want to discuss what happens on the line c.foo().

Original, Misleading Question

Note: Not all of this actually happens with each individual invokevirtual opcode. Hint: If you want to understand Java method invocation, don’t read just the documentation for invokevirtual!

At the bytecode level, the meat of c.foo() will be the invokevirtual opcode, and, according to the documentation for invokevirtual, more or less the following will happen:

  1. Look up the foo method defined in compile-time class MyClass. (This involves first resolving MyClass.)
  2. Do some checks, including: Verify that c is not an initialization method, and verify that calling MyClass.foo wouldn’t violate any protected modifiers.
  3. Figure out which method to actually call. In particular, look up c’s runtime type. If that type has foo(), call that method and return. If not, look up c’s runtime type’s superclass; if that type has foo, call that method and return. If not, look up c’s runtime type’s superclass’s superclass; if that type has foo, call that method and return. Etc.. If no suitable method can be found, then error.

Step #3 alone seems adequate for figuring out which method to call and verifying that said method has the correct argument/return types. So my question is why step #1 gets performed in the first place. Possible answers seem to be:

  • You don’t have enough information to perform step #3 until step #1 is complete. (This seems implausible at first glance, so please explain.)
  • The linking or access modifier checks done in #1 and #2 are essential to prevent certain bad things from happening, and those checks must be performed based on the compile-time type, rather than the run-time type hierarchy. (Please explain.)

Revised Question

The core of the javac compiler output for the line c.foo() will be an instruction like this:

invokevirtual i

where i is an index to MyClass’ runtime constant pool. That constant pool entry will be of type CONSTANT_Methodref_info, and will indicate (maybe indirectly) A) the name of the method called (i.e. foo), B) the method signature, and C) the name of compile time class that the method is called on (i.e. MyClass).

The question is, why is the reference to the compile-time type (MyClass) needed? Since invokevirtual is going to do dynamic dispatch on the runtime type of c, isn’t it redundant to store the reference to the compile-time class?

Answer

It is all about performance. When by figuring out the compile-time type (aka: static type) the JVM can compute the index of the invoked method in the virtual function table of the runtime type (aka: dynamic type). Using this index step 3 simply becomes an access into an array which can be accomplished in constant time. No looping is needed.

Example:

class A {
   void foo() { }
   void bar() { }
}

class B extends A {
  void foo() { } // Overrides A.foo()
}

By default, A extends Object which defines these methods (final methods omitted as they are invoked via invokespecial):

class Object {
  public int hashCode() { ... }
  public boolean equals(Object o) { ... }
  public String toString() { ... }
  protected void finalize() { ... }
  protected Object clone() { ... }
}

Now, consider this invocation:

A x = ...;
x.foo();

By figuring out that x’s static type is A the JVM can also figure out the list of methods that are available at this call site: hashCode, equals, toString, finalize, clone, foo, bar. In this list, foo is the 6th entry (hashCode is 1st, equals is 2nd, etc.). This calculation of the index is performed once – when the JVM loads the classfile.

After that, whenever the JVM processes x.foo() is just needs to access the 6th entry in the list of methods that x offers, equivalent to x.getClass().getMethods[5], (which points at A.foo() if x’s dynamic type is A) and invoke that method. No need to exhaustively search this array of methods.

Note that the method’s index, remains the same regardless of the dynamic type of x. That is: even if x points to an instance of B, the 6th methods is still foo (although this time it will point at B.foo()).

Update

[In light of your update]: You’re right. In order to perform a virtual method dispatch all the JVM needs is the name+signature of the method (or the offset within the vtable). However, the JVM does not execute things blindly. It first checks that the cassfiles loaded into it are correct in a process called verification (see also here).

Verification expresses one of the design principles of the JVM: It does not rely on the compiler to produce correct code. It checks the code itself before it allows it to be executed. In particular, the verifier checks that every invoked virtual method is actually defined by the static type of the receiver object. Obviously, the static type of the receiver is needed to perform such a check.

Categories
discuss

In which cases it makes sense to use factory classes instead of static functions?

Currently I have created a ABCFactory class that has a single method creating ABC objects. Now that I think of it, maybe instead of having a factory, I could just make a static method in my ABC Method. What are the pro’s and con’s on making this change? Will it not lead to the same? I don’t foresee having other classes inherit ABC, but one never knows!

Thanks

Answer

In reality, if you want to get the benefits of a factory class, you need the static method in it’s own class. This will allow you to later create new factory classes, or reconfigure the existing one to get different behaviors. For example, one factory class might create Unicorns which implement the IFourHoovedAnimal interface. You might have an algorithm written that does things with IFourHoovedAnimal’s and needs to instantiate them. Later you can create a new factory class that instead instantiates Pegasus’s which also implement IFourHoovedAnimal’s. The old algorithm can now be reused for Pegasus’s just by using the new factory! To make this work both the PegasusFactory and the UnicornFactory must inherit from some common base class(usually an abstract class).

So you see by placing the static method in it’s own factory class, you can swap out factory classes with newer ones to reuse old algorithms. This also works for improving testability, because now unit tests can be fed a factory that creates mock objects.

I have done the latter before (static factory method on the class that you are creating instances of) for very small projects, but it was only because I needed it to help refactor some old code, but keep changes to a minimum. Basically in that case I had factored out a chunk of code that created a bunch of ASP.NET controls, and stuff all those controls into a user control. I wanted to make my new user control property based, but it was easier for the old legacy code to create the user control with a parameter based constructor.

So I created a static factory method that took all the parameters, and then instanced the user control and set it’s properties based on the parameters. The old legacy code used this static method to create the user control, and future code would use the “prettier” properties instead.

Categories
discuss

How to add response headers based on Content-type; getting Content-type before the response is committed

I want to set the Expires header for all image/* and text/css. I’m doing this in a Filter. However:

  • before calling chain.doFilter(..) the Content-type is not yet “realized”
  • after calling chain.doFilter(..) the Content-type is set, but so is content-length, which forbids adding new headers (at least in Tomcat implementation)

I can use the extensions of the requested resource, but since some of the css files are generated by richfaces by taking them from inside jar-files, the name of the file isn’t x.css, but is /xx/yy/zz.xcss/DATB/....

So, is there a way to get the Content-type before the response is committed.

Answer

Yes, implement HttpServletResponseWrapper and override setContentType().

class AddExpiresHeader extends HttpServletResponseWrapper {
    private static final long ONE_WEEK_IN_MILLIS = 604800000L;

    public AddExpiresHeader(HttpServletResponse response) {
        super(response);
    }

    public void setContentType(String type) {
        if (type.startsWith("text") || type.startsWith("image")) {
            super.setDateHeader("Expires", System.currentTimeMillis() + ONE_WEEK_IN_MILLIS);
        }
        super.setContentType(type);
    }
}

and use it as follows:

chain.doFilter(request, new AddExpiresHeader((HttpServletResponse) response));
Categories
discuss

Execute code on window close in GWT

I’d like to do something like this:

Window.addWindowClosingHandler(new Window.ClosingHandler() {

    @Override
    public void onWindowClosing(ClosingEvent event) {
        event.setMessage("Really?");

        // If user clicks 'ok' in the dialog, execute code below. Else skip the code and return to window.

        // CODE that does stuff goes here.
    }
});

How do I capture the input from the dialog?

Answer

There need to be two handlers, one Window.ClosingHandler and one CloseHandler. See below. This will make sure, if ‘cancel’ is clicked in the dialog, the CloseHandler isn’t triggered. But if ‘ok’ is clicked, the CloseHandler is executed and will run the necessary code. This could be used for releasing db locks, neatly closing open sessions, etc.

Window.addWindowClosingHandler(new Window.ClosingHandler() {

    @Override
    public void onWindowClosing(ClosingEvent event) {
        event.setMessage("You sure?");
    }
});

Window.addCloseHandler(new CloseHandler<Window>() {

    @Override
    public void onClose(CloseEvent<Window> event) {
        //Execute code when window closes!
    }
});
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..