My favorites | Sign in
Project Logo
                
Search
for
Updated Jan 10, 2009 by coekie
Labels: Featured
ExampleUsage  
Example usages

Introduction

This page shows some examples of what the gentyref library does.

Examples

Check if a type is a supertype of another type, including type parameters.

You use TypeToken to refer to specific types, and GenericTypeReflector.isSuperType to check if a type is a supertype of another. Given the following interface and classes:

	interface Processor<T> {
		void process(T t);
	}
	
	class StringProcessor implements Processor<String> {
		public void process(String s) {
			System.out.println("processing " + s);
		}
	}
	
	class IntegerProcessor implements Processor<Integer> {
		public void process(Integer i) {
			System.out.println("processing " + i);
		}
	}

We can check that a certain class is the right kind of Processor:

	/*
	 * Returns true if processorClass extends Processor<String>
	 */
	public boolean isStringProcessor(Class<? extends Processor<?>> processorClass) {
		// Use TypeToken to get an instanceof a specific Type
		Type type = new TypeToken<Processor<String>>(){}.getType();
		// Use GenericTypeReflector.isSuperType to check if a type is a supertype of another
		return GenericTypeReflector.isSuperType(type, processorClass);
	}

For example

Get the exact return type of a method, including type parameters Given the following classes:

	abstract class Lister<T> {
		public List<T> list() {
			return null;
		}
	}
	
	class StringLister extends Lister<String> {
	}

The return type of the Lister.list() method is List<T>. For StringLister, this would be List<String>. But, if we simply get the return type from java, we get List<T>:

	Method listMethod = StringLister.class.getMethod("list");
	Type returnType = listMethod.getGenericReturnType();

Then returnType is List<T>, not what we want. To get the exact return type, use GenericTypeReflector.getExactReturnType:

	Type exactReturnType = GenericTypeReflector.getExactReturnType(listMethod, StringLister.class);

Now exactReturnType is List<String>.


Sign in to add a comment
Hosted by Google Code