Java Cheat Sheet

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.


  • 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() {{
    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("");
    } catch (MalformedURLException e) {


  • 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" );


  • 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() );
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] );
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.
  • Choose a Maven 2 archetype from the local repository when creating a project
mvn archetype:create -DarchetypeCatalog=file://$HOME/.m2
Phase Description
validatevalidate the project is correct and all necessary information is available.
generate-sourcesgenerate any source code for inclusion in compilation.
process-sourcesprocess the source code, for example to filter any values.
generate-resourcesgenerate resources for inclusion in the package.
process-resourcescopy and process the resources into the destination directory, ready for packaging.
compilecompile the source code of the project.
process-classespost-process the generated files from compilation, for example to do bytecode enhancement on Java classes.
generate-test-sourcesgenerate any test source code for inclusion in compilation.
process-test-sourcesprocess the test source code, for example to filter any values.
generate-test-resourcescreate resources for testing.
process-test-resourcescopy and process the resources into the test destination directory.
test-compilecompile the test source code into the test destination directory
testrun tests using a suitable unit testing framework. These tests should not require the code be packaged or deployed.
prepare-packageperform 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)
packagetake the compiled code and package it in its distributable format, such as a JAR.
pre-integration-testperform actions required before integration tests are executed. This may involve things such as setting up the required environment.
integration-testprocess and deploy the package if necessary into an environment where integration tests can be run.
post-integration-testperform actions required after integration tests have been executed. This may including cleaning up the environment.
verifyrun any checks to verify the package is valid and meets quality criteria.
installinstall the package into the local repository, for use as a dependency in other projects locally.
deploydone 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 ${}. 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.


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.


  • 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.
  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);
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:
$> ./ --host=

Debug Techniques

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

JVM Switches


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


  • Get NetBeans to stop adding VIM swap files to .cvsignore or svn:ignore
    • Open $HOME/.netbeans/6.1/config/Preferences/org/netbeans/
    • 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


java/javacheatsheet.txt · Last modified: 2009/07/20 13:36 by dallen
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki