I have a problem with templates and static methods a in Java (version 6), which can be divided into two sub-problems:
First, I need to find a way how I can return a template Iterable (from a static context) that creates new instances of some subclass (e.g. B) of an abstract class (e.g. A) in each iteration. (Background: I need to translate one object (e.g. String) from iterable to another object). I found a way with / generics templates:
import java.util.HashSet; import java.util.Iterator; public class Test { public static <T extends A> Iterable<T> getIterable(final Iterator<String> i) { return new Iterable<T>() { public Iterator<T> iterator() { return new Iterator<T>() { public boolean hasNext() { return i.hasNext(); } public T next() { try { return T.factory(i.next()); } catch (Exception e) { e.printStackTrace(); return null; } } public void remove() { i.remove(); } }; } }; } public static void main(String[] args) { HashSet<String> st = new HashSet<String>(); st.add("x1"); Iterable<B> bi = getIterable(st.iterator()); for (B b : bi) { System.out.println(b); } } }
In addition, I defined the following class hierarchy:
abstract class A { public static <T extends A> T factory(String c) { return null; } } class B extends A { String s; public B (String s) { this.s = s; } public static B factory(String s) { return new B(s); } }
The general way seems to work (in principle). However, the called static factory method will always be one of the superclass A, although the pattern T is of type B.
I am looking for any ideas / suggestions on how to call a factory subclass, i.e. the class that comes with the template <T> (for example, B). Any help is much appreciated!
(Note: I found that in Java 7 you can use interfaces and inherit / override static methods, but I'm bound to Java 6 ...)
source share