I'm trying to implement a class that isolates a part of a object, and replaces the part with with something else. The part of the object may not have the same type as the object itself.
A simple example would be a class that takes the string "--12--", isolates the ascii number, and replaces it with the next natural number. So, the whole sequence would be "--12--" -> "12" -> 12 -> 13 -> "13" -> "--13--"
.
With this in mind, I implemented the following:
public abstract class Replacer<Outer, Inner>
{
protected abstract Inner decompose(Outer something);
protected abstract Outer compose(Inner something);
protected abstract Inner inner_replace(Inner something);
public Outer replace(Outer something)
{
Inner s = decompose(something);
s = inner_replace(s);
return compose(s);
}
}
Now, I want to be able to compose a series of Replacers - stack them, so that each one computes its inner_replace
by using the "lower" Replacer:
public abstract class ComposableReplacer<Outer, Inner> extends Replacer<Outer, Inner>
{
protected Replacer<Inner, ?> child;
@Override
public Outer replace(Outer something)
{
Inner s = decompose(something);
s = inner_replace(s);
if (child!=null)
s= child.replace(s);
return compose(s);
}
}
So, far, this works correctly, but now I'm trying to write a convenience method to take a couple of ComposableReplacers and stack them automatically:
public static <I, O> ComposableReplacer<I, O> compose(ComposableReplacer<?, ?>... rs)
{
for (int i=0; i<rs.length-1; i++)
rs[i].child= rs[i+1];
return rs[0];
}
This fails, since each ComposableReplacer's inner type must be the outer type of its child and the compiler can't infer that from a array of ComposableReplacer<?, ?>
.
Is it possible to do this in java (and still have type safety)?
EDIT
To be clear, the problem is declaring a method that takes an array of ComposableReplacer
and stacks/chains them, with type safety.