I got a generic interface with one method accepting a parameter of the generic type:
public interface ComponentRenderer<T extends GuiComponent> {
public void draw(T component);
}
Furthermore I have an abstract class, that declares a variable of this interface type using a bounded wildcard:
public abstract class GuiComponent extends Gui {
private ComponentRenderer<? extends GuiComponent> componentRenderer;
public void draw() {
this.componentRenderer.draw(this);
}
//and a setter and getter for the ComponentRenderer
}
And a subclass, wich set a implementation for the componentRenderer:
public class GuiButton extends GuiComponent {
public GuiButton(/* ... */) {
//...
this.setComponentRenderer(new FlatButtonRenderer());
}
where FlatButtonRenderer is implemented as:
public class FlatButtonRenderer implements ComponentRenderer<GuiButton> {
#Override
public void draw(final GuiButton component) {
//...
}
}
I can't see where I got something wrong, but the call componentRenderer.draw(this) in GuiComponent does not work with the following error:
As far as I understand this, it says me, that I can't use GuiComponent because it does not derive from GuiComponent, what makes no sense. I've also tried ? super GuiComponent, which will accept the draw() call, but then does not accept the implementation of FlatButtonRenderer
I do not understand this syntax error, does anyone have an idea, how I need to change the code?
EDIT:
When I use my IDE's code completion on the call of draw(), it says me, that draw accept one argument of type "null", so for some reason, it is not able to figure out, wich type the argument should be...
The problem is that ? extends GuiComponent means "one specific subtype of GuiComponent, but unknown which".
The compiler does not know that this is of the right GuiComponent subtype for the ComponentRenderer. It could be that the renderer only can work with some other specific subclass.
You have to use some kind of self-type pattern to do this in a type-safe way. That way you kind of "connect" the type variable of the renderer with the type of the GuiComponent subclass.
Example:
class Gui {}
interface ComponentRenderer<T extends GuiComponent<T>> {
public void draw(T component);
}
// T is the self-type. Subclasses will set it to their own type. In this way this class
// can refer to the type of its subclasses.
abstract class GuiComponent<T extends GuiComponent<T>> extends Gui {
private ComponentRenderer<T> componentRenderer;
public void draw() {
this.componentRenderer.draw(thisSub());
}
public void setComponentRenderer(ComponentRenderer<T> r) {}
// This method is needed for the superclass to be able to use 'this'
// with a subclass type. Sub-classes must override it to return 'this'
public abstract T thisSub();
//and a setter and getter for the ComponentRenderer
}
// Here the self-type parameter is set
class GuiButton extends GuiComponent<GuiButton> {
public GuiButton(/* ... */) {
//...
this.setComponentRenderer(new FlatButtonRenderer());
}
class FlatButtonRenderer implements ComponentRenderer<GuiButton> {
#Override
public void draw(final GuiButton component) {
//...
}
}
#Override
public GuiButton thisSub() {
return this;
}
}
This is originally (I think) called the curiously recurring template pattern. This answer explains it more.
In GuiComponent, change your declaration of componentRenderer to this:
ComponentRenderer<GuiComponent> componentRenderer;
Related
This isn't a JavaFX question, but I'm trying to write an interface in JavaFX that declares a class to be Viewable. Viewable classes are meant to have a view() method that returns a Node object representing that Viewable. Simple so far, but here's where it gets complicated. The returned Node should be guaranteed to have a getViewable() method that returns the Viewable object it represents. How do I accomplish this? My first instinct was to try something like this:
interface Viewable<V extends Viewable<V>>{
<N extends Node&View<V>>N view();
}
interface View<V extends Viewable<V>>{
V getViewable();
}
Which at first appears sound, and allows classes like the following:
class ViewableObject implements Viewable<ViewableObject>{
#Override public ObjectView view(){
return new ObjectView();
}
class ObjectView extends Pane implements View<ViewableObject>{
#Override public ViewableObject getViewable(){
return ViewableObject.this;
}
}
}
However, for some reason, this class also compiles:
class ViewableObject implements Viewable<ViewableObject>{
#Override public Pane view(){
return new Pane();
}
}
Pane is a Node, but it does not implement View, so why does this class compile? I would think this is violating the contract of the view() method. Even stranger, the same class fails to compile when Pane is replaced with Object:
class ViewableObject implements Viewable<ViewableObject>{
#Override public Object view(){//complains this is not an #Override
return new Object();
}
}
What's going on here? Is there a flaw in my understanding of generics? How can I get this to work as intended?
You don't want to use a generic method in this case, since your goal is to fix the type of view()'s return value. A generic method lets the caller determine the concrete types. So really you're doing the exact opposite of enforcing.
I think you'd want to build the type parameter for the Node's type into the interface definitions, which will enforce that view() returns the correct type. Maybe something like this:
interface Viewable<V extends Viewable<V, N>, N extends Node & View<V, N>> {
N view();
}
interface View<V extends Viewable<V, TNode>, TNode extends Node & View<V, TNode>> {
V getViewable();
}
class ViewableObject implements Viewable<ViewableObject, ViewableObject.ObjectView> {
#Override
public ObjectView view() {
return new ObjectView();
}
class ObjectView extends Pane implements View<ViewableObject, ObjectView> {
#Override
public ViewableObject getViewable() {
return ViewableObject.this;
}
}
}
If you take a look at the byte code for the declaration of Viewable.view(), you'll see that the compiler selects the first type bound to specify as the actual return type for the method. Here are the relevant lines of the output from the IntelliJ byte code viewer:
// declaration: N view<N extends org.cumberlw.viewtest.Node, org.cumberlw.viewtest.View<V>>()
public abstract view()Lorg/cumberlw/viewtest/Node;
So when overriding you can specify any type that is covariant with the first type only and the compiler will accept it. If you switch the order of the type bounds, this is what you'll see in the byte code viewer:
// declaration: N view<N extends org.cumberlw.viewtest.View<V>, org.cumberlw.viewtest.Node>()
public abstract view()Lorg/cumberlw/viewtest/View;
Notice that the byte code says the return value is View now. So now your second example won't compile because Pane is not a subclass of View. Neither order of the parameters will let the third example compile because Object is not a subclass of Node or View.
Overriding a method with a generic return type with multiple bounds can easily produce runtime errors too. The compiler only enforces that return types be covariant with the first type bound, so you can return a type that does not conform to the second type bound. For example this compiles fine, but crashes at runtime:
interface DogLike {
void bark();
}
interface CatLike {
void meow();
}
class Dog implements DogLike {
#Override
public void bark() {
System.out.println("Woof");
}
}
interface MoreauMachine {
<H extends DogLike & CatLike > H createHybrid();
}
class MalfunctioningDogCatFactory implements MoreauMachine {
#Override
public DogLike createHybrid() {
//Compile with -Xlint:unchecked to see a warning here:
//Warning:(84, 20) java: createHybrid() in org.cumberlw.viewtest.MalfunctioningDogCatFactory implements <H>createHybrid() in org.cumberlw.viewtest.MoreauMachine
//return type requires unchecked conversion from org.cumberlw.viewtest.DogLike to H
return new Dog();
}
public static void main(String[] args) {
MoreauMachine factory = new MalfunctioningDogCatFactory();
//crashes!
//Exception in thread "main" java.lang.ClassCastException: org.cumberlw.viewtest.Dog cannot be cast to org.cumberlw.viewtest.CatLike
factory.createHybrid().meow();
}
}
I have problem with comparing java generic type if it is type of Void or not. In other words I'm trying to ensure if my generic type T is Void or not.
My sample implementation:
public abstract class Request<T>{
private T member;
protected void comparing(){
if(T instanceof Void) // this make error "Expression expected"
runAnotherMethod();
//if I type
if(member instanceof Void) //Incovertible types; cannot cast T to java.lang.Void
runAnotherMethod();
}
protected void runAnotherMethod(){...}
}
public class ParticularRequest extends Request<Void>{
}
I've tried to compare id via instanceof, Class<T> and Class<Void>, T.class and Void.class.
But the AndroidStudio show me error in every tried case :(
can you help me how to compare it?
thanks.
When using java generics you often need to ask for the class of the generic type in the constructor so that you can actually work with the class. I guess, that is a confusing sentence so just see the example below:
public abstract class Request<T> {
private Class<T> clazz;
// constructor that asks for the class of the generic type
public Request(Class<T> clazz) {
this.clazz = clazz;
}
// helper function involving the class of the generic type.
// in this case we check if the generic type is of class java.lang.Void
protected boolean isVoidRequest(){
return clazz.equals(Void.class);
}
// functionality that depends on the generic type
protected void comparing() {
if (isVoidRequest()) {
runAnotherMethod();
}
}
// ...
}
When you subclass you must pass the class of the generic type to the super constructor.
public class LongRequest extends Request<Long> {
public LongRequest() {
super(Long.class);
}
}
public class VoidRequest extends Request<Void> {
public VoidRequest() {
super(Void.class);
}
}
You can store a private member that is of the generic type of the class.
public abstract class Request<T> {
private T memberOfGenericType;
protected void comparing() {
if (memberOfGenericType instanceof Sometype)
runAnotherMethod();
}
protected void runAnotherMethod() { ... }
public T getMemberOfGenericType() {
return memberOfGenericType;
}
public void setMemberOfGenericType(T value) {
this.memberOfGenericType = value;
}
}
This way, at Runtime, the memberOfGenericType will have the type of Sometype and you will be able to compile the if statement. You can also verify that the memberOfGenericType is Sometype at Runtime, by using the getter I've added.
Anyhow, as a side note, I would say that there's no need of generic type, if you don't use it as a type for a member, method or method parameter and then you should re-consider your design. Also, in particular, the type Void is not instantiable, so you wouldn't be able to pass a valid instance for the class member, which more or less makes the if statement useless.
You can't use T like that. You need some instance to compare. For example some member or parameter:
public abstract class Request<T> {
T member;
protected void comparing(T param){
if(member instanceof Void)
runAnotherMethod();
if(param instanceof Void)
runAnotherMethod();
}
protected void runAnotherMethod(){...}
}
A better approach to accessing the parameter class, used by Guice, is to use the fact that, while a generic class cannot access its own 'class' arguments, its subclasses do have access to these arguments: see https://stackoverflow.com/a/18610693/15472
If you need this, either use Guice' TypeLiterals, or reimplment their logic.
Since there are no objects that are instances of the Void type in Java you can't use instanceof here.
null is the only value that is a member of the type Void. So maybe what you want to do is this?:
if (memberOfGenericType == null)
runAnotherMethod();
About the type Void
No objects of type Void can be created because the class only has a private constructor and it is never invoked from within the class. Void is usually used in these situations:
To get a Class object that represents the return type of methods declared to return void.
As a placeholder type argument, when the fields and variables of that type are not meant to be used.
At run-time T is compiled as Object, and the actual class is unknown. As others said, you should maintain an instance of your parametrized type, but this is not automatic: You need to instantiate it, and the constructor T() cannot be used.
Also java.lang.Void cannot be instantiated, so you should use another class, like a self-made Void class.
Try something like this:
public final class Void {}; // cannot use java.lang.Void, so create another class...
public abstract class Request<T> {
protected abstract T member(); // A member would need to be initialized...
protected void comparing(T param){
if(member() instanceof Void) // Use our Void not java.lang.Void
runAnotherMethod();
}
protected void runAnotherMethod(){...}
}
public class ParticularRequest extends Request<Void>{
#Override
protected Void member() { return new Void(); } // Could be optimized...
}
Edit:
I do not see, why would you need this, however.
If you have different children for different types, then you also could have different implementations, too.
Something like this (types and methods are for example only):
public abstract class Request<T> {
protected abstract T method();
}
public class RequestInt extends Request<Integer> {
#Override
protected Integer method() {...}
}
public class RequestText extends Request<String> {
#Override
protected String method() {...}
}
(Working in Java)
I have an abstract class with generic typing throughout the whole class:
public abstract class ConnectionProcessor<T>
{
public void process()
{
for (List<T> resultsPage : connection)
{
processPage(resultsPage);
}
}
protected abstract void processPage(List<T> resultsPage);
}
I have another class that extends said abstract class, with the following declaration:
public class AlbumProcessor<Album> extends ConnectionProcessor
{
#Override
protected void processPage(List resultsPage)
{
//Do stuff here specific to Album
}
}
This declaration works fine, but in processPage I want to do Album-specific things, and I try to avoid casting when I don't need to use it. I would PREFER this to be the method declaration:
protected void processPage(List<Album> resultsPage)
But this doesn't meet the requirements for overriding processPage from ConnectionProcessor. Why is this? How can I get the desired behavior? I would think that in AlbumProcessor I could just plug in <Album> everywhere ConnectionProcessor has <T>, but that just isn't the case.
Try
//extend prameterized version of ConnectionProcessor<T> with Album as actual type argument
public class AlbumProcessor extends ConnectionProcessor<Album> {
instead of
public class AlbumProcessor<Album> extends ConnectionProcessor {
When you do the above you are exteding the raw version of the generic type ConnectionProcessor<T> and introducing a new formal type parameter - Album (like T) which is not an actual type argument in that case.
That's because you didn't bind your super class Generic type T to Album.
Rather, this is what you should do:
public class AlbumProcessor extends ConnectionProcessor<Album>
So, when you'll override your method processPage, (using an IDE), it will generate code as follows:
#Override
protected void processPage(List<Album> resultsPage)
{
//Do stuff here specific to Album
}
public class AlbumProcessor extends ConnectionProcessor<Album>
Try: -
public class AlbumProcessor extends ConnectionProcessor<Album>
{
#Override
protected void processPage(List<Album> resultsPage)
{
//Do stuff here specific to Album
}
}
You need to bind your super class with the type you want to give as a type parameter to your List in your method declaration..
How bout something more like this.
import java.util.List;
public abstract class ConnectionProcessor<T>
{
public void process()
{
System.out.println("Hello");
}
protected abstract void processPage(List<? extends T> resultsPage);
}
...
public class ProcessorImpl extends ConnectionProcessor<Album> {
protected void processPage(List<? extends Album> resultsPage) {
for(Album result : resultsPage){
System.out.println(result.getAlbumName());
}
}
}
...
public class Album {
public String getAlbumName(){
return "Sweet Smooth SOunds of the 70's";
}
}
I have some troubles with a method having a typed List parameter, inherited from another (typed) class.
Let's keep it simple :
public class B<T> {
public void test(List<Integer> i) {
}
}
The B class has a useless generic T, and test() want an Integer List.
Now if I do :
public class A extends B {
// don't compile
#Override
public void test(List<Integer> i) {
}
}
I get a "The method test(List) of type A must override or implement a supertype method" error, that should not happen.
But removing the type of the list works... although it doesn't depend on the class generic.
public class A extends B {
// compile
#Override
public void test(List i) {
And also defining the useless generic below to use the typed list
public class A extends B<String> {
// compile
#Override
public void test(List<Integer> i) {
So I'm clueless, the generic of B should have no influence on the type of the test() list. Does anyone have an idea of what's happening?
Thanks
You're extending the raw type of B, not the generic one. The raw one effectively does not have a test(List<Integer> i) method, but a test(List) method.
If you switch to raw types, all generics are replaced by raws, regardless of whether their type was filled in or not.
To do it properly, do
public class A<T> extends B<T>
This will use the generic type B<T>, which includes the method you want to override.
When you remove use a class without generics (and use it raw), all generics from class methods are forgotten.
Due this reason when you inform the generic type on the second case you get it working.
This:
class T<G> {
public void test(G g);
}
in this case:
class A extends T {
}
will look like this:
class T {
public void test(Object g);
}
This was a java puzzle presented on Google IO 2011 you can see video here
First off, I want to say there is no use case for this. The only thing I am trying to do is explore if this is possible.
What I am trying to do is "rebrand" the return signature of a method in the base interface to that of a child interface.
The goal: declare and implement a method once, but vary the return type to match subinterfaces. I have figured out how to achieve this in some cases, but it breaks down in certain situations.
Imagine if I have base interface B and it has a method B doWork(). Also, there is an implementation of B that implements doWork(). Due to the nature of doWork(), this implementation should be the only one that exists.
Now, this is pretty easy to do with Generics. For the above example:
interface B<T extends B> {
T doWork();
}
class BImpl<T extends B> implements B<T> {
#Override
public T doWork() { return something; }
}
And the child interface/impl would look like this maybe:
interface C extends B<C> {
void somethingCSpecific();
}
class CImpl extends BImpl<C> implements C {
#Override
public void somethingCSpecific() { }
}
Anyone constructing CImpl would see that doWork() returns a C.
C obj = new CImpl().doWork() // The money shot. No casting needed.
And here is where it breaks down... Imagine B now looks like this:
public interface B<T extends B> {
T thisOrThat(T that);
boolean something();
}
And I want to do this in BImpl:
class BImpl<T extends B> implements B<T> {
#Override
public T thisOrThat(T that) {
if (that.something())
return that;
return this; // Error!! _this_ might be a different T than _that_.
}
#Override
public boolean something() { return whatever; }
}
Note where the error happens.
Obviously, this can't work without an unsafe and dubious cast. But if I knew that the implementation of this in the above thisOrThat method was the same as the implementation of that, everything would be ok.
So, to my question. Is there a way to restrict this and that to the same type, without knowing that type a priori?
Or maybe is there a different way to go about doing this, but having the same result? Namely only having to declare AND implement thisOrThat() just once, yet have the return type adapt to the subinterface?
Thanks.
Make your class BImpl abstract and add a view method to it which is implemented by the specific classes extending your abstract base class:
public abstract class BImpl<T extends B<T>> implements B<T> {
#Override
public T thisOrThat(T that) {
if (that.something())
return that;
return this.asT();
}
#Override
public boolean something() {
// TODO Auto-generated method stub
return false;
}
protected abstract T asT();
}
Every of your classes still needs to implement T asT() then, but this is simple and compiles without warning:
public class C extends BImpl<C> implements B<C> {
#Override
protected C asT() {
return this;
}
}
If I understand your problem correctly, then the way to solve it is with a sort of self-referential generic: B<T extends B<T>>.
I think what you want is class BImpl implements B<BImpl>, in which case everything type checks normally.