Category Archives: Java

Check Generic type

Using JMS which is not implemented with Generics, I decided to add some “genericity”.
The problem is that, because of type erasure, I can’t use the simple instanceof operator, the solution I used is to pass the class of the Generic when I use it:

import java.io.Serializable;

public class Handler {

    public Handler() {
        super();
    }
    
    private Class clazz;

    public Handler(Class clazz) {
        super();
        this.clazz = clazz;
    }

    public T extract(Object o) {
        if (!(o.getClass().isAssignableFrom(clazz)))
            throw new RuntimeException("explicite message");
        return (T) o;
    }
    
    public static void main(String[] args) {
        Handler handler = new Handler(String.class);
        
        System.out.println(handler.extract(new Integer("11")));//This throw an Exception
        
        System.out.println(handler.extract(new Integer("11")));//This is ok
    }
}

Now it works, but I will try to find a more elegant solution to avoid the clazz parameter.

Define the Java version in Maven

Directly in the pom.xml (resource definition is also included):

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
...
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>**/*</include>
            </includes>
            <excludes>
                <exclude>profiles/**</exclude>
            </excludes>
            </resource>
            <resource>
                <directory>src/main/resources/profiles/${profile.name}</directory>
                <includes>
                    <include>*.properties</include>
                    <include>*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>