Java Generics - Iterating with upper bounded and lower bounded wildcards - java

I have 2 Interfaces:
public interface Flash { public void flash(int level); } and
public interface SuperFlash extends Flash { public void flash(int level, boolean repeat); }
Then I have a custom collection class which should hold any number of things implementing Flash or SuperFlash. The class declaration looks something like
public class FlashyThings<? extends Flash>.
So the class can hold instances of type Flash and its subtype(s).
Inside the class FlashyThings, I am using an ArrayList to hold all of these objects:
private ArrayList<? extends Flash> things;
So far so good, now, when I try to iterate over the collection, is there a way to know/infer the dynamic type of the objects without using instanceof (as in the next snippet)?
for (Flash f : this.things) {
if (f instanceof SuperFlash) { // <-- :(
// SuperFlash things
} else {
// Flash things
}
}
This is the upper bounded side of the medal, now to the lower bounded side
To begin with, I had to change the class declaration to
public class FlashyThings
as lower bounded wildcards are not allowed in the class declaration. The ArrayList declaration now looks like:
private ArrayList<? super SuperFlash> things;
Now iterating over the collection becomes:
for (Object o : this.things) { // <-- :((
// All things are of type Object which is *really* not cool
if (o instanceof SuperFlash) { // <-- :(
// SuperFlash things
} else {
// Flash things
}
}
So I'm pretty much stuck where I began.
What would be the recommended way to iterate over such a construct? To summarise, what I want to achieve having is
the interface hierarchy described at the very top
the class FlashyThings being parameterisable
iterating over the ArrayList things, taking into account the dynamic type of its contents (without having to do the instanceof check)

What you need to do is create an abstract FlashyThing that does as much of the shared methods as possible in the abstract class, leaving only the stuff that is dependent on knowing you have a Flash or SuperFlash to the subclass. For example (publics and privates left out for brevity):
abstract class AbstractFlashyThing<F extends Flash> {
List<F> flashes;
AbstractFlashyThing() {
flashes = new ArrayList<F>();
}
void doOperations() {
for (F flash : flashes) {
doOperation(flash);
}
}
abstract void doOperation(F flash);
}
Note how the generic type F is used as a place holder wherever possible.
Example subclass
class SuperFlashyThing extends AbstractFlashyThing<SuperFlash> {
#Override
void doOperation(SuperFlash superFlash) {
// do super flash stuff
}
}
Subclass is a concrete implementation rather than a generic class, so its instatiation is as follows.
SuperFlashyThing thing = new SuperFlashyThing();
// as opposed to the following
SuperFlashyThing<SuperFlash> thing = new SuperFlashyThing<SuperFlash>();

Maybe I don't quite understand the problem, but why are you making everything so complicated, instead of just using polymorphism? This is what the Object Oriented Paradigm is designed to do. Example:
Flash.java
public class Flash {
public void doSomething() {
System.out.println("Flash doSomething()");
}
}
SuperFlash.java
public class SuperFlash extends Flash {
#Override
public void doSomething() {
System.out.println("SuperFlash doSomething()");
}
}
FlashyThings.java
public class FlashyThings {
private ArrayList<Flash> things = new ArrayList<>();
public ArrayList<Flash> getThings() {
return things;
}
public void doSomething(){
for (Flash thing : things) {
thing.doSomething();
}
}
}
ExampleMain.java
public class ExampleMain {
public static void main(String[] args) {
Flash first = new Flash();
SuperFlash second = new SuperFlash();
Flash third = new Flash();
FlashyThings things = new FlashyThings();
things.getThings().add(first);
things.getThings().add(second);
things.getThings().add(third);
things.doSomething();
}
}

What about using an enum ?
public enum FlashType
{
Flash, SuperFlash;
}
Add a method for checking the flash type of any object of type Flash:
public interface Flash
{
void flash(int level);
FlashType getType();
}
Then iterate over private ArrayList<? extends Flash> things;
for (Flash f : this.things)
{
if (f.getType() == FlashType.SuperFlash)
{
// SuperFlash things
}
else if (f.getType() == FlashType.Flash)
{
// Flash things
}
}
or iterate over ArrayList<? super SuperFlash> things;
for (Object o : this.things)
{
final Flash f = (Flash)o;//this cannot failed: SuperFlash extends Flash
if (f.getType() == FlashType.SuperFlash)
{
// SuperFlash things
}
else if (f.getType() == FlashType.Flash)
{
// Flash things
}
}

Related

How to create a new object based on interface implementation

Firstly, I believe my question is badly worded but don't really understand how to phrase it.
I have a starting interface that is being implemented by a number of classes. What I want to do is to see if there is a way to create a new object such that I am being passed the generic interface, then based on the method .getClass().getSimpleName(), create a new object based on that string.
Is the only way to create a switch case statement? As the number of implementing classes are too many (about 100 or so).
Reference code:
public interface MyInterface {
public void someMethod();
}
then I would have my implementing classes:
public class MyClass1 implements MyInterface {
public void someMethod() { //statements }
}
public class MyClass2 implements MyInterface {
public void someMethod() { //statements }
}
public class MyClass3 implements MyInterface {
public void someMethod() { //statements }
}
What I want to have in the end is another class which is passed an argument of type MyInterface, get the simple name from that and create a new instance of MyClassX based on that simple name.
public class AnotherClass {
public void someMethod(MyInterface interface) {
if (interface == null) {
System.err.println("Invalid reference!");
System.exit(-1);
} else {
String interfaceName = interface.getClass().getSimpleName();
/**
* This is where my problem is!
*/
MyInterface newInterface = new <interfaceName> // where interfaceName would be MyClass1 or 2 or 3...
}
}
}
Any help is highly appreciated!
You can use reflection for this:
public void someMethod(MyInterface myInterface) {
Class<MyInterface> cl = myInterface.getClass();
MyInteface realImplementationObject = cl.newInstance(); // handle exceptions in try/catch block
}
This is a common problem with many solutions. When I face it, I never use reflection because it is difficult to maintain if it is part of a big project.
Typically this problem comes when you have to build an object based on a user selection. You can try a Decorator pattern for that. So, instead of building a different object for each option. You can build a single object adding functionality depending on a selection. For instance:
// you have
Pizza defaultPizza = new BoringPizza();
// user add some ingredients
Pizza commonPizza = new WithCheese(defaultPizza);
// more interesting pizza
Pizza myFavorite = new WithMushroom(commonPizza);
// and so on ...
// then, when the user checks the ingredients, he will see what he ordered:
pizza.ingredients();
// this should show cheese, mushroom, etc.
under the hood:
class WithMushroom implements Pizza {
private final Pizza decorated;
public WithMushroom(Pizza decorated) {
this.decorated = decorated;
}
#Override
public Lizt<String> ingredients() {
List<String> pizzaIngredients = this.decorated.ingredients();
// add the new ingredient
pizzaIngredients.add("Mushroom");
// return the ingredients with the new one
return pizzaIngredients;
}
}
The point is that you are not creating an object for each option. Instead, you create a single object with the required functionality. And each decorator encapsulates a single functionality.

checking type of reference in generics java

I am currently building a game in java(turn based RPG) and am facing a problem in inventory UI. Perhaps my problem is well known or has a simple solution, but having never had any training, I will still ask the question.
While displaying the inventory after selecting an item I check if that item implements the SpecificItemWorker interface , that is, acts on a specific GameObject that has to be passed in to its takeAction() method. While selecting that object which has to be passed, I display all the possible candidate objects for the user to select. For example, suppose the user selects a UpgradeParchment that acts on any object that implements Upgradable interface. Here, I initiate a ItemSelector that displays all the items in the inventory that implements Upgradable. However with a different class , the interface that the object needs to implement in order to be a possible candidate will differ.(Note that some objects act on the game environment rather than on a specific object, but we are not considering that case here.).Now instead of hard-coding the possible interfaces in a switch case statement , i want it to be dynamic.I tried to use generics, but it does not allow to check if an object is an instanceof of the Type parameter.
The following code gives a compile error:
package ui;
import objects.Collectable;
public class ItemSelector<T> {
public void test(Collectable ob) {
if (ob instanceof T) {// compile error
// do work
}
}
}
Does anyone know how this can be achieved?Thanks for any help.
Looking for a speedy reply,
Thanks.
EDIT :
The parameter in the testAction() method will be of type Collectable as in my inventory class, there is only a list of Collectable objects.Similarly, in my test method , I have updated the types.Although it is a minor change, sorry for any inconvenience.Collectable is also an interface.
Due to runtime type erasure, you need to provide what's called a type token to the class:
public class ItemSelector<T> {
private final Class<T> clazz;
public ItemSelector(Class<T> clazz) {
this.clazz = clazz;
}
public void test(GameObject ob) {
if (clazz.isInstance(ob)) {// use token to check type
// do work
}
}
}
This requires a class object to be passed to the constructor, usually by passing a class literal, eg MyClass.class
There is a way to check the type with class.getTypeName().
I assume the SpecificItemWorker is a game object as shown in the code.
package stackoverflow.question39718130;
public class SpecificItemWorker extends GameObject {
}
package stackoverflow.question39718130;
public class ItemSelector<T> {
private T t;
public ItemSelector(final T t) {
this.t = t;
}
public T getT() {
return t;
}
public void test(final GameObject ob) {
/*if (ob instanceof T) {// compile error
// do work
}*/
if (t.getClass().getTypeName() == ob.getClass().getTypeName()) {
System.out.println("Grab item.");
} else {
System.err.println("No item found.");
}
}
}
There is a test example to pass the GameObject.
package stackoverflow.question39718130;
public class GameObjectTest {
public static void main(final String[] args) {
specificItemWorkerTest();
}
public static void specificItemWorkerTest() {
final GameObject specificItemWorker = new SpecificItemWorker();
final ItemSelector<GameObject> selector = new ItemSelector<>(specificItemWorker);
selector.test(specificItemWorker);
}
}
I hope I understood you right with the SpecificItemWorker. Please let me know if this fits to your solution.

Java: abstract or generic list that all derived classes must implement

I am making a component-based system for a game engine in Java.
I have different system classes to take care of different things, e.g., PhysicsSystem, RenderSystem, EditorSystem and so on. All classes inherits from BaseSystem, which in turn implements an interface ISystem.
I would like all of my system classes to have an ArrayList, but the type in each of them may differ, meaning that the RenderSystem might have a list of RenderComponents, while the PhysicsSystem has a list of PhysicsBodyComponents.
Is it possible to define a generic or abstract list in either the BaseSystem class or the ISystem interface that all the derived classes then implements? I have little experience with generics, so I am a bit confused by this.
This is my current code. As you can see, I created a second list for the derived class, which is kind of a waste.
interface ISystem
{
boolean AddToSystem(Component c);
}
abstract class BaseSystem implements ISystem
{
// can I make this list generic, so it can store any type in derived classes?
// e.g., Component, IRenderable, IPhysics, etc.
protected List<Component> _componentList;
}
class RenderSystem extends BaseSystem
{
// need to make a second list that stores the specific render components
List<IRenderable> _renderList = new ArrayList<IRenderable>();
void Update()
{
for (IRenderable r : _renderList)
r.Render(); // this code is specific to the IRenderable components
}
#Override
public boolean AddToSystem(Component c)
{
boolean succesfullyAdded = false;
if (c instanceof IRenderable)
{
succesfullyAdded = true;
_renderList.add((IRenderable) c);
} else
throw new RuntimeException("ERROR - " + c.Name() + " doesn't implement IRenderable interface!");
return succesfullyAdded;
}
}
Sure, assuming that all your components implement IComponent use something like this:
interface ISystem<ComponentType extends IComponent> {
public boolean AddToSystem(ComponentType c);
}
If you do not want to have a hard type dependency, you can remove the extends IComponent, but it will make handling lists of systems harder.
I think you need something like this
private static abstract class AbstractClass<T> {
final List<T> objects = new ArrayList<T>();
}
private static class ComponentHolder extends AbstractClass<Component> {
public void add(final Component c) {
objects.add(c);
}
public Component getComponent(final int index) {
return objects.get(index);
}
}
In your example, it would be something like this:
abstract class BaseSystem<T> implements ISystem
{
protected List<T> _componentList = new ArrayList<T>();
}
class RenderSystem extends BaseSystem<IRenderable>
{
void Update()
{
for (IRenderable r : _componentList)
r.Render(); // this code is specific to the IRenderable components
}
#Override
public boolean AddToSystem(Component c)
{
boolean succesfullyAdded = false;
if (c instanceof IRenderable)
{
succesfullyAdded = true;
_componentList.add((IRenderable) c);
} else
throw new RuntimeException("ERROR - " + c.Name() + " doesn't implement IRenderable interface!");
return succesfullyAdded;
}
}

Downcasting and polymorphism without using instanceof? (Java)

Here's the sort of thing I'm trying to do:
class Foo {
private ArrayList<Widget> things; //Contains WidgetA, WidgetB and WidgetAB objects
//...
void process(int wIndex) {
process(things.get(wIndex);
}
private void process(WidgetA w) {
//Do things
}
private void process(WidgetB w) {
//Do other things
}
private void process(WidgetAB w) {
//Do completely different things
}
}
abstract class Widget {
//...
}
class WidgetA extends Widget {
//...
}
class WidgetB extends Widget {
}
class WidgetAB extends WidgetA {
}
Basically, a separate class gets an array index from user input, and passes it to the process(int) method, which is supposed to kick off a type-specific process() method to process the object at the passed index. The problem is that the objects are treated as Widget objects, not WidgetA, etc. I could loop through the types using instanceof, I guess, but I'm trying to avoid using that.
The logic in the process() methods needs to access private fields in the Foo class, so moving them to the Widget subclasses might not be the best idea.
So the question is, is there a way for the correct process() method to be called for a given Widget subtype, without using instanceof?
Yes, have a look at the Visitor pattern - also known as double dispatch.
Another potential solution is to use Java's reflection API's. Example:
class Foo {
private ArrayList<Widget> things; //Contains WidgetA, WidgetB and WidgetAB objects
//...
void process(int wIndex) {
Widget theWidget = things.get(wIndex);
try {
Class type = theWidget.getClass();
Class[] arg_types = new Class[]{type};
this.getMethod("process", arg_types).invoke(this, theWidget);
} catch (Exception e) {
//Could be SecurityException or NoSuchMethodException
}
}
private void process(WidgetA w) {
//Do things
}
private void process(WidgetB w) {
//Do other things
}
private void process(WidgetAB w) {
//Do completely different things
}
}
abstract class Widget {
//...
}
class WidgetA extends Widget {
//...
}
class WidgetB extends Widget {
}
class WidgetAB extends WidgetA {
}
The issue here being that you have to have defined a process() method for each type of object in the things list or an exception will be thrown at run-time. The compiler will not warn you if you are missing an implementation.

Refactoring code in Java, alternatives to large if statement

I'm refactoring some code in a project I'm working on and I ran into a large if/else if statement that follows the format:
if (changer instanceof AppleChanger)
{
panel = new ApplePanel();
}
else if (changer instanceof OrangeChanger)
{
panel = new OrangePanel();
}
Now my first impulse was to refactor it using polymorphism to have it appear like
panel = changer.getChangerPanel();
However unfortunately the class package doesn't have access to the panel package.
My next impulse was to create a PanelChooser class with an overloaded method:
PanelChooser.getPanel(changer);
//Overloaded Method
public Panel getPanel(OrangeChanger changer)
{
Panel orangePanel = new OrangePanel();
return orangePanel;
}
public Panel getPanel(AppleChanger changer)
{
Panel applePanel = new ApplePanel();
return applePanel;
}
Is this a good solution or is there a better way to solve this?
The fundamental 'problem' here is that you have parallel class hierarchies. You're not going to be able to replace that if statement without some fairly heavy refactoring. Some suggestions are on c2 wiki.
The best you can do, and possibly a perfectly fine solution, is to move the if statement into a 'factory' class and make sure it's not duplicated anywhere else.
I think its good that your first impulse didn't work :) Otherwise you would couple you changer code (which should be something about logic) to UI code (panel) and its wrong.
Now I can offer you the following solution:
create an interface PanelCreator with method Panel createPanel like this:
interface PanelCreator {
Panel createPanel();
}
Now, provide 2 implementations:
public class OrangePanelCreator implements PanelCreator{
Panel createPanel() {
return new OrangePanel();
}
}
public class ApplePanelCreator implements PanelCreator {
Panel createPanel() {
return new ApplePanel();
}
}
And now come the interesting part:
Create a Map, PanelCreator> this would act like a registry for your panels:
Map<Class<Changer>, PanelCreator> registry = new HashMap<>;
registry.put(OrangeChanger.class, new OrangePanelCreator());
registry.put(AppleChanger.class, new ApplePanelCreator());
And in your code now you can do the following thing:
panel = registry.get(changer.getClass()).createPanel();
I think it will be more elegant since you can easily change implementations of creators given the changer.
Hope this helps
If there is more than one of this if/else constructs in the code dependending on the instance type of a Changer, you can use the visitor pattern like this:
public interface ChangerVisitor {
void visit(OrangeChanger changer);
void visit(AppleChanger changer);
...
}
public class ChangerVisitorEnabler<V extends ChangerVisitor> {
public static <V extends ChangerVisitor> ChangerVisitorEnabler<V> enable(V) {
return new ChangerVisitorEnabler<V>(visitor);
}
private final V visitor;
private ChangerVisitorEnabler(V visitor) {
this.visitor = visitor;
}
public V visit(Charger changer) {
if (changer instanceof OrangeChanger) {
visitor.visit((OrangeChanger)changer);
} else if (changer instanceof AppleChanger) {
visitor.visit((AppleChanger)changer);
} else {
throw new IllegalArgumentException("Unsupported charger type: " + changer);
}
return visitor;
}
}
Now you have a single type check code block and a type safe interface:
public PanelChooser implements ChangerVisitor {
public static Panel choosePanel(Changer changer) {
return ChangerVisitorEnabler.enable(new PanelChooser()).visit(changer).panel;
}
private Panel panel;
private PanelChooser() {
}
void visit(OrangeChanger changer) {
panel = orangePanel();
}
void visit(AppleChanger changer) {
panel = applePanel();
}
}
The usage is very simple:
panel = PanelChooser.choosePanel(chooser);
Perhaps you can do:
public Panel getPanel(Changer changer)
{
String changerClassName = changer.class.getName();
String panelClassName = changerClassName.replaceFirst("Changer", "Panel");
Panel panel = (Panel) Class.forName(panelClassName).newInstance();
return panel;
}
I don't program in Java, but that is what I would try if this were in C#. I also don't know if this would work with your packages.
Good luck!
I don't see enough existing code and design at whole. So probably, first of all I would try to move the code with panel instantiation to the same place where Changer instance is created. Because choosing a Panel is the same decision as choosing a Changer.
If a selected Changer is dynamically selected, you may just create these panels and then show/hide them accordingly.
I'd do the following:
Have an interface PanelChooser with a single method returning a Panel for a Changer.
Have an implementation ClassBasedPanelChooser returning a panel when the Change implements a certain class and null otherwise. The class and the panel to be returned get passed in in the constructor.
Have another implementation CascadingPanelChooser which takes a list of PanelChoosers in the constructor arguments and on call of its method asks each PanelChooser to provide a panel until it receives a not null panel, then it returns that panel.
Your solution will not work, because Java selects the method based on the compiletime type (which here is probably Changer). You could use a Map<Class<? extends Changer>, Panel> (or Map<Class<? extends Changer>, Class<? extens Panel>> if you need to create new instances every time). This solution does require extra work if you need this to work for - yet unknown - subclasses of for example OrangeChanger.
eg for a single instance per Changer subclass
changerToPanel.get(changer.getClass());
or if you need new instances:
changerToPanelClass.get(changer.getClass()).newInstance();
The other option would be to go for your initial hunch, and make Changer know about Panel.
Take a look at the Factory and Abstract Factory Patterns.
The Factory Pattern is a creational pattern as it is used to control class instantiation. The factory pattern is used to replace class constructors, abstracting the process of object generation so that the type of the object instantiated can be determined at run-time.
Abstract Factory Pattern is a creational pattern, as it is used to control class instantiation. The abstract factory pattern is used to provide a client with a set of related or dependent objects. The family of objects created by the factory is determined at run-time according to the selection of concrete factory class.
Do not use instanceof.Why polymorphism fails
The only place to use instanceof is inside equals method.
To answer your question. Follow this link.
Credits to Cowan and jordao .
Using Reflection.
public final class Handler {
public static void handle(Object o) {
for (Method handler : Handler.class.getMethods()) {
if (handler.getName().equals("getPanel") &&
handler.getParameterTypes()[0] == o.getClass()) {
try {
handler.invoke(null, o);
return;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
throw new RuntimeException("Can't handle");
}
public static void handle(Apple num) { /* ... */ }
public static void handle(Orange num) { /* ... */ }
Chain of Responsibility
public abstract class Changer{
private Changer next;
public final boolean handle(Object o) {
boolean handled = doHandle(o);
if (handled) { return true; }
else if (next == null) { return false; }
else { return next.handle(o); }
}
public void setNext(Changer next) { this.next = next; }
protected abstract boolean doHandle(Object o);
}
public class AppleHandler extends Changer{
#Override
protected boolean doHandle(Object o) {
if (!o instanceof Apple ) {
return false;
}
OrangeHandler.handle((Orange) o);
return true;
}
}

Categories

Resources