Remember back in the days of college when you were allowed to make one sheet of notes for math exams? Well, think of this as a cheat sheet for you Java exam.

Instantiation

  • Implement default constructor inline when defining a class. This trick is great for unit tests. Notice the use of double brackets.

Client client = new Client() {{
    setId(1);
    setName("Client 1");
}};
  • Instantiate a static final property in a static block with use of try/catch exception

private static final URL SOME_URL_CONSTANT;

static {
    URL url = null;
    try {
        url = new URL("http://example.com");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    SOME_URL_CONSTANT = url;
}

Logging

  • Disable commons-logging in a pinch. This must be done before commons-logging is used.

System.setProperty( "org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog" );

Generics

  • Find the actual type used by a generic return type. Synthetic methods are those that are overridden.
    The code assumes that the class method defined as T getCode() and resides on an object parameterized using T=java.lang.String.

for ( Method method : candidate.getClass().getMethods() ) {
    if ( "getCode".equals( method.getName() ) && !method.isSynthetic() ) {
        System.out.println( "Type is: " + method.getGenericReturnType() );
        break;
    }
}
Type is java.lang.String
  • Find the actual parameterized type used when the object was instantiated.
    The code assumes the class interface is CustomInterface<T> and candidate is an instance of an implementation where T=java.lang.Integer.

for ( Type interfaceType : candidate.getClass().getGenericInterfaces() ) {
    if ( interfaceType instanceof ParameterizedType && ( (ParameterizedType) interfaceType ).getRawType().equals( CustomInterface.class ) ) {
        System.out.println( "Type is: " + ( (ParameterizedType) interfaceType ).getActualTypeArguments()[0] );
        break;
    }
}
Type is java.lang.Integer
  • Return the same type that is used in the arguments, without knowing ahead of time what that type may be.

public <T> T giveMeWhatICameFor( T whatIWant ) {
    return belongings.get( whatIWant );
}
  • Get type defined for collection of field

Method method = beanClass.getDeclaredMethod("setIntegers", List.class);
System.out.println(((ParameterizedType) method.getGenericParameterTypes()[0]).getActualTypeArguments()[0]);

Maven 2

  • Update the released version in the metadata.xml files when deploying

$> mvn deploy -DupdateReleaseInfo=true
  • Force a version of a dependency. The transitive mechanism will normally select the highest version referenced. However, you can force a particular version.

<dependency>
  <groupId>com.example</groupId>
  <artifactId>artifact</artifactId>
  <version>[1.1.12]</version>
</dependency>
  • Choose a Maven 2 archetype from the local repository when creating a project

mvn archetype:create -DarchetypeCatalog=file://$HOME/.m2
Phase Description

validate

validate the project is correct and all necessary information is available.

generate-sources

generate any source code for inclusion in compilation.

process-sources

process the source code, for example to filter any values.

generate-resources

generate resources for inclusion in the package.

process-resources

copy and process the resources into the destination directory, ready for packaging.

compile

compile the source code of the project.

process-classes

post-process the generated files from compilation, for example to do bytecode enhancement on Java classes.

generate-test-sources

generate any test source code for inclusion in compilation.

process-test-sources

process the test source code, for example to filter any values.

generate-test-resources

create resources for testing.

process-test-resources

copy and process the resources into the test destination directory.

test-compile

compile the test source code into the test destination directory

test

run tests using a suitable unit testing framework. These tests should not require the code be packaged or deployed.

prepare-package

perform any operations necessary to prepare a package before the actual packaging. This often results in an unpacked, processed version of the package. (Maven 2.1 and above)

package

take the compiled code and package it in its distributable format, such as a JAR.

pre-integration-test

perform actions required before integration tests are executed. This may involve things such as setting up the required environment.

integration-test

process and deploy the package if necessary into an environment where integration tests can be run.

post-integration-test

perform actions required after integration tests have been executed. This may including cleaning up the environment.

verify

run any checks to verify the package is valid and meets quality criteria.

install

install the package into the local repository, for use as a dependency in other projects locally.

deploy

done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

  • I know that Maven has access to implicit variables such as $\{project.build.directory}. Where can I find this list?

  • How do I fetch an artifact into my local repository without a project?

To do anything in Maven 2, you have to have a POM file in place (pom.xml). First create a minimalistic POM file containing the library you wish to download.

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>none</groupId>
    <artifactId>none</artifactId>
    <version>1.0</version>
    <dependencies>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.0.20070617</version>
        </dependency>
    </dependencies>
</project>

Then use the Maven 2 dependency plugin to resolve the dependency into your local repository.

mvn dependency:resolve
  • The maven antrun plugin executes the Ant tasks at the end of each phase.

JDBC (MySQL)

  • View the SQL and parameter values used in a PreparedStatement. Place a breakpoint on the following method and click on the callingStatement variable in the debugger. The Statement#toString() method shows both the SQL query and the parameter list just as you would see it if you spelled it out in a SQL query. If you only want to see prepared statements, you should make the breakpoint conditional, checking that the sql variable is null. Otherwise, you get all the connection initialization queries as well.

com.mysql.jdbc.Connection#execSQL(
  Statement callingStatement,
  String sql,
  int maxRows,
  Buffer packet,
  int resultSetType,
  int resultSetConcurrency,
  boolean streamResults,
  String catalog,
  boolean unpackFields,
  boolean isBatch
)

Deep clone

Generally you should try to avoid cloning objects blindly (you are probably doing something wrong in your application). But if you really need to do it, one approach is to serialize then deserialize the object (all containing objects must be serializable):

ByteArrayOutputStream byteArrOs = new ByteArrayOutputStream();
ObjectOutputStream objOs = new ObjectOutputStream(byteArrOs);
objOs.writeObject(this);

ByteArrayInputStream byteArrIs = new ByteArrayInputStream(byteArrOs.toByteArray());
ObjectInputStream objIs = new ObjectInputStream(byteArrIs);
Object deepCopy = objIs.readObject();

JBoss AS

  • Allow JBoss AS to accept connections on IP addresses other than localhost:

$> ./run.sh --host=0.0.0.0

Debug Techniques

  • Print the current stacktrace to the console in Linux: CTRL+\

JVM Switches

Eclipse

  • Negative search

(?s)\A((?!string_not_present).)*\Z (check Regular Expression box)

NetBeans

  • Get NetBeans to stop adding VIM swap files to .cvsignore or svn:ignore

    • Open $HOME/.netbeans/6.1/config/Preferences/org/netbeans/core.properties

    • Remove everything in the IgnoredFiles property after the last pipe character (|) (i.e., |^\\..*$) and append ^\.svn$

    • Restart NetBeans

    • You can also find this setting under the Files tab in the Options

Hibernate