开发者

Reference a kind of that without using parameterized types in Java

I have a class that needs to maintain or know about (has-a) reference to three kinds of other classes. What is the best way to provide such a reference?

class Hello<T extends IsLetter> {
    private T refOtherClass;
}
// getter and setter for refOtherClass here

interface IsLetter {}

class A implements IsLetter {
    private String a = "A data";
}
class B implements IsLetter {
    private String b = "B data";
}

now is there a way to do this without using parameterized types? Since if Im using parameterized types, any class that uses Hello will need to provide it when creating it (which is fine) but also when using Hello, i cant just say

Hello hi = new Hello(); 
// set the refOtherClass ...
hi.getRefOtherClass(); // and here use the refOtherClass like it was of type A
or B,开发者_Go百科 when using hi I need to provide, again, the type that was put in hi.

Hints?


You can of course use a cast:

A a = (A) hi.getRefOtherClass();

What generics do here is move the verification of this cast to an earlier stage - compile time. If you don't use generics, and if you try to cast to the wrong type, you'll get the error at runtime.

This is in case you need to work with a concrete type. If the interface IsLetter (better call it just Letter) has all the methods, just make the method return Letter and work with the interface.

You can get the exact class of an object by calling object.getClass(), or perhaps use an if-clause like if (a instanceof A)


Your poor explanation probably didn't get you any anwers. But here is a try of what i think you are asking.

So first you need to do this:

Hello<A> hi = new Hello<A>(); 

Because you are using generics in Java.

Now you can do

A a = hi.getRefOtherClass();
//or
IsLetter a = hi.getRefOtherClass();

Finally, you should probaby put a method on you interface like so:

interface IsLetter{ String getValue();}

Which of course then you can do a.getValue(); And because of the beauty of OO, you can return "B VALUE" from B or "A Value" from A.


I'm not clear on why you want to do this without generics - this is exactly the sort of situation generics make clearer:

class Hello<T extends IsLetter> { 
   public T getRefOtherClass(){ ... }
 }

class A implements IsLetter { ... }

class B implements IsLetter { ... }

Hello hi = new Hello<A>();
A a = hi.getRefOtherClass();

You can only get rid of the parameterization by casting the output of the get method, which is messier, or by subclassing the Hello so that the parameterization is "encapsulated" in your subclassing (which might make sense in some cases, although not in a simple example like this ) e.g.

 class HelloA extends Hello<A> {...
  A a = new HelloA.get()

But again, you're not getting rid of the generics, you're just shifting them around.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜