Can't invoke a static class method obtained as an extended ("extends") generic in Java 6?

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 { /* this is where things go wrong: * * T is considered as class A and not B */ 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:

 /* super class */ abstract class A { public static <T extends A> T factory(String c) { /* returns nothing, should never be called */ return null; } } /* child class */ 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 ...)

+4
source share
1 answer

The Java static makes sense to the compiler: it allows the compiler to statically bind a method call to a method at compile time. Therefore, the compiler writes the call of the A.factory(String) method to the received byte code when compiling the string return T.factory(i.next()).

Obviously, you wanted to override the factory method in B to have dynamic behavior when the program starts. For this behavior, you must remove the static .

+3
source

Source: https://habr.com/ru/post/1491108/


All Articles