When I write the method this way. I get this warning:
BaseEvent is a raw type. References to generic type BaseEvent
should be parameterized
#Override
public <T extends BaseEvent> void actionPerformed(T event) { ... }
The code still runs fine, although the warning sign is annoying. When I write the code this way the warning goes away.
#Override
public <T> void actionPerformed(BaseEvent<T> event) { ... }
With the previous message, It doesn't guarantee that is a subClass of BaseEvent. So I changed it again:
#Override
public <T extends EventObject> void actionPerformed(BaseEvent<T> event) { ... }
#Override
public <T extends BaseEvent<T>> void actionPerformed(BaseEvent<T> event) { ... }
BaseEvent class is a class I made that extends EventOBject
public abstract class BaseEvent<T> extends EventObject
{
private String eventType;
// Constructor
public BaseEvent(Object source, String type)
{
super(source);
eventType = type;
}
public String getEventType() { return eventType; }
}
All the methods seem to work fine. But I was wondering which is the better solution.
Where do you use T in BaseEvent definition? Define it in the following way
public abstract class BaseEvent extends EventObject
then you won't get a warning with
#Override
public void actionPerformed(BaseEvent event) { ... }
UPDATE
Suppose your BaseEvent really required to be parametrized. Then write following
#Override
public <T> void actionPerformed(BaseEvent<T> event) { ... }
This will give you a parametrized method.
UPDATE 1
It doesn't guarantee that is a subClass of BaseEvent.
It does. <T> is a parameter for method template. This parameter goes to BaseEvent<T> which is subclass of EventObject by definition.
UPDATE 2
Do not use generics at the beginning of your learning. Generics are just for additional self testing. Use raw types. Then when you start to feel them, you will parametrize them correctly.
The type parameter T is never used in the class definition. You might be able to remove the type parameter from BaseEvent:
public abstract class BaseEvent extends EventObject { ... }
and just define your method without a type parameter:
#Override
public void actionPerformed(BaseEvent event) { ... }
The best solution is the one that avoids the warnings and guarantees your type safety at compile time.
If the type of T in BaseEvent doesn't matter, couldn't you just use your first one and parameterize BaseEvent? Do something like:
#Override
public <T extends BaseEvent<?>> void actionPerformed(T event) { ... }
Alternatively, it looks like your BaseEvent class does not actually use T for anything - why is it there?
Related
Here's a simplified version of the object model that I am working on.
public class GenericsTest {
public interface FooInterface {
public void foo();
}
public class Bar implements FooInterface {
public void foo() {}
}
public interface GenericInterface <T> {
public T func1();
}
public class Service implements GenericInterface<Bar> {
#Override
public Bar func1() {
return null;
}
}
public class GenericBar <S extends GenericInterface<FooInterface>> {
public S s;
public GenericBar() {}
}
public static void main(String[] args) {
GenericBar<Service> serviceGenericBar; // <-- compilation error at this line
<... more code ...>
}
}
Compiler Error: type argument GenericsTest.Service is not within bounds of type-variable S
IDE (intellij) shows some more details on the error: Type parameter 'GenericsTest.Service' is not within its bound; should implement GenericsTest.GenericInterface<GenericTests.FooInterface>
Service class is implementing the GenericInterface. I have looked at few other SO questions with the same error but they don't offer clues for this particular scenario. Any ideas on how to fix this?
The problem is exactly what two compilers have told you: type Service is not within the bounds that type GenericBar requires of its type parameter, S. Specifically, GenericBar requires the S parameter of its realizations to be bound to a type that extends GenericInterface<FooInterface>. Service does not satisfy that requirement.
Service implements GenericInterface<Bar>, which is neither GenericInterface<FooInterface> nor an extension of that type, the fact that Bar implements FooInterface notwithstanding. You cannot assign a List<String> to a variable of type List<Object>, either, for basically the same reason.
You can resolve the compilation error by modifying the definition of class GenericBar like so:
public class GenericBar <S extends GenericInterface<? extends FooInterface>> {
public S s;
public GenericBar() {}
}
Whether this is what you actually want to use is an entirely different question, which only you can answer.
When you change Service to implement GenericInterface the code would compile.
public class Service implements GenericInterface<FooInterface> {
#Override
public Bar func1() {
return null;
}
}
Or if you prefer to limit Service to base only on Bar you could change GenericBar so it will become more generic:
public class Service implements GenericInterface<Bar> {
#Override
public Bar func1() {
return null;
}
}
public class GenericBar<S extends GenericInterface<? extends FooInterface>> {
public S s;
public GenericBar() {
}
}
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;
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