I am trying to write a class as:
public class Article<T<? extends ManageGenericArticleInDTO>, U> implements Serializable {
private T<? extends ManageGenericArticleInDTO> userInput;
private U severData;
public Article<T<? extends ManageGenericArticleInDTO>, U>() {
super();
}
public void setUserInput(T<? extends ManageGenericArticleInDTO> userInput) {
this.userInput = userInput;
}
public T<? extends ManageGenericArticleInDTO> getUserInput() {
return userInput;
}
public void setSeverData(U severData) {
this.severData = severData;
}
public U getSeverData() {
return severData;
}
}
So that I can write these:
Article<UpdateManageArticleInDTO<ManageGenericArticleInDTO>, UpdateCentralPOSMArticleDTO> article = new Article<UpdateManageArticleInDTO<ManageGenericArticleInDTO>, UpdateCentralPOSMArticleDTO>();
Article<AddManageArticleInDTO<ManageCentralPOSMArticleInDTO>, AddArticleStepDTO> article = new Article<AddManageArticleInDTO<ManageCentralPOSMArticleInDTO>, AddArticleStepDTO>(); // ManageCentralPOSMArticleInDTO extends ManageGenericArticleInDTO
I am getting compilation error that Error(7,32): > expected, Error(7,33): illegal start of type etc. In my understanding the Type reference will be replaced by the actual class., Can't I define the class in this?
If I do this:
public class AddArticleInBean<T, U> implements Serializable {
private T userInput;
private U severData;
public AddArticleInBean() {
super();
}
public void setUserInput(T userInput) {
this.userInput = userInput;
}
public T getUserInput() {
return userInput;
}
public void setSeverData(U severData) {
this.severData = severData;
}
public U getSeverData() {
return severData;
}
}
This errors are not anymore appearing, but I am getting warning that T and U are non-serializable.
I think you are missing opening and closing brackets
It should be,
Article<UpdateManageArticleInDTO<ManageGenericArticleInDTO>, UpdateCentralPOSMArticleDTO> article = new Article<UpdateManageArticleInDTO<ManageGenericArticleInDTO>, UpdateCentralPOSMArticleDTO>();
Article<AddManageArticleInDTO<ManageCentralPOSMArticleInDTO>, AddArticleStepDTO> article = new Article<AddManageArticleInDTO<ManageCentralPOSMArticleInDTO>, AddArticleStepDTO>();
Related
Background
I learned Factory pattern, and the power of generics and I'm attempting to piece them together.
Here are my efforts
Without generic input parameter - No warnings
public abstract class ArtifactCreator {
public abstract void setArtifacts(String workflowInput);
}
public class FooArtifactCreator extends ArtifactCreator {
#Override
public void setArtifacts(String input) {
return null;
}
}
public class BarArtifactCreator extends ArtifactCreator {
#Override
public void setArtifacts(String input) {
return null;
}
}
public class Factory {
public ArtifactCreator getArtifactCreator(String domain) {
if (domain == "foo") {
return new FooArtifactCreator()
} else if (domain == "bar") {
return new BarArtifactCreator()
}
return null;
}
}
My whole problem is the workflowInput is relegated to the type String. But I want it to be some generic POJO.
With generics - I get warnings in Factory.java and Store.java that I want to get rid of correctly. (I want to be using generics for my use-case the right way).
Raw use of parameterized class 'ArtifactCreator' on both the files in Store.java and Factory.java
Unchecked call to 'setArtifacts(T)' as a member of raw type 'ArtifactCreator' in Store.java
public abstract class ArtifactCreator {
public abstract void setArtifacts(T workflowInput);
}
public class FooArtifactCreator extends ArtifactCreator<FooInput> {
#Override
public void setArtifacts(FooInput input) {
return null;
}
}
public class BarArtifactCreator extends ArtifactCreator<BarInput> {
#Override
public void setArtifacts(BarInput input) {
return null;
}
}
public class Factory {
public ArtifactCreator getArtifactCreator(String domain) {
if (domain == "foo") {
return new FooArtifactCreator()
} else if (domain == "bar") {
return new BarArtifactCreator()
}
return null;
}
}
public class Input {
private String domain;
private String otherInput;
}
public class Store {
private final Factory factory;
public Store(Factory factory) {
this.factory = factory;
}
public ArtifactCreator getCaseClosureArtifactFactory(Input req) {
ArtifactCreator artifactCreator = factory.setArtifacts(req.getDomain());
//In reality - Create either FooInput or BarInput depending on
//`otherInput` field in `Input` POJO. Assume that there will be another
//factory/HashMap to return the input needed
FooInput input = new FooInput();
artifactCreator.setArtifacts(input);
}
}
One way I can think of solving my problems is do something like:
public class WorkflowInput {
private FooInput input;
private BarInput input;
}
public abstract class ArtifactCreator {
public abstract void setArtifacts(WorkflowInput workflowInput);
}
public class FooArtifactCreator extends ArtifactCreator {
#Override
public void setArtifacts(WorkflowInput input) {
FooInput input = input.getFooInput(); //Extract specific input
}
}
public class BarArtifactCreator extends ArtifactCreator {
#Override
public void setArtifacts(WorkflowInput input) {
BarInput input = input.getBarInput(); //Extract specific input
}
}
This feels a bit unecessary to keep some fields in WorkflowInput null.
I created a java project to apply my GraphTheory course and enhance my java skills.
In this project :
I created a class Sommet<S>(Vertex in English) with an attribute Id with a generic type called <S>.
I created a class Arc<S>(Edge in English) with two attributes Sommet(Vertex).
I created a class EnsembleArc which is an HashSet of Arc
I also created a class ArcValue which inherit from Arc and have an int attribute Valeur(Value in English)
Here everything is fine and I dont have any problem.
But then I created a class EnsembleArcValue which inherit from EnsembleArc because every method from EnsembleArc will be useful to EnsembleArcValue.
But I also want EnsembleArcValue to be an HashSet of ArcValue (and I dont want an Arc which is not an ArcValue). And with the inheritance EnsembleArcValue is able to have an "simple" Arc in his Set.
So my question after all this explanation is :
Is there a way for EnsembleArcValue to inherit from EnsembleArc but will only accept an ArcValue in his Set.
Here is an image of The UML Project
I hope it will help to understand my problem (dont look at the bottom).
Here is the code :
public class Sommet<S>
{
//attributes
private S id;
public Sommet(S s)
{
setId(s);
}
public S getId()
{
return id;
}
public void setId(S s)
{
assert s!= null: "Objet null passé en paramètre";
id = s;
}
#SuppressWarnings("unchecked")
#Override
public boolean equals(Object obj)
{
boolean callback;
if(obj.getClass()!=getClass())
{
callback=false;
}
else
{
if(((Sommet<S>)obj).getId().equals(getId()))
{
callback=true;
}
else
{
callback=false;
}
}
return callback;
}
#Override
public int hashCode()
{
return getId().hashCode();
}
#Override
public String toString()
{
return getId().toString();
}
}
public class Arc<S>
{
private Sommet<S> depart;
private Sommet<S> arrivee;
public Arc(Sommet<S> dep, Sommet<S> arr)
{
setDepart(dep);
setArrivee(arr);
}
#Override
public String toString()
{
String str="("+getDepart().getId()+","+getArrivee().getId()+")";
return str;
}
public Sommet<S> getDepart()
{
return depart;
}
public Sommet<S> getArrivee()
{
return arrivee;
}
public void setDepart(Sommet<S> depart)
{
this.depart = depart;
}
public void setArrivee(Sommet<S> arrivee)
{
this.arrivee = arrivee;
}
#SuppressWarnings("unchecked")
#Override
public boolean equals(Object obj)
{
boolean callback;
if(obj.getClass()!=getClass())
{
callback=false;
}
else
{
if(((Arc<S>)obj).getDepart().equals(getDepart())&&((Arc<S>)obj).getArrivee().equals(getArrivee()))
{
callback=true;
}
else
{
callback=false;
}
}
return callback;
}
#Override
public int hashCode()
{
return getArrivee().hashCode()+getDepart().hashCode();
}
}
public class ArcValue<S,V> extends Arc<S>
{
private V valeur;
public ArcValue (Sommet<S> depart, Sommet<S> arrivee, V valeur)
{
super(arrivee,depart);
this.valeur=valeur;
}
public V getValeur()
{
return valeur;
}
}
import java.util.HashSet;
public class Ensemble<E> extends HashSet<E> implements Cloneable
{
private static final long serialVersionUID = -4354387895748449845L;
public Ensemble ()
{
super();
}
public Ensemble (Ensemble<E> ensemble)
{
for (E e : ensemble)
{
add(e);
}
}
public String toString()
{
StringBuffer str=new StringBuffer("{");
for(E e: this)
{
str=str.append(e.toString()+",");
}
str.setCharAt(str.length()-1, '}');
return str.toString();
}
#SuppressWarnings("unchecked")
#Override
public Ensemble<E> clone()
{
return (Ensemble<E>)super.clone();
}
}
public class EnsembleArc<S> extends Ensemble<Arc<S>>
{
public EnsembleArc(Ensemble<Arc<S>> ensemble)
{
super(ensemble);
}
public EnsembleArc()
{
super();
}
private static final long serialVersionUID = -4099925554493145279L;
public EnsembleSommet<S> listSucc(Sommet<S> sommet)
{
EnsembleSommet<S> XSucc=new EnsembleSommet<S>();
for (Arc<S> arc : this)
{
if (arc.getDepart()==sommet)
{
XSucc.add(arc.getArrivee());
}
}
return XSucc;
}
public EnsembleSommet<S> listPred(Sommet<S> sommet)
{
EnsembleSommet<S> XPred=new EnsembleSommet<S>();
for (Arc<S> arc : this)
{
if (arc.getArrivee()==sommet)
{
XPred.add(arc.getDepart());
}
}
return XPred;
}
public void add(Sommet<S> depart,Sommet<S>arrivee)
{
add(new Arc<S>(depart,arrivee));
}
#Override
public EnsembleArc<S> clone ()
{
return (EnsembleArc<S>)super.clone();
}
}
//import java.util.Collection;
public class EnsembleArcValues<S,V> extends EnsembleArc<S> //implements Collection<ArcValue<S,V>>
{
//TODO faire en sorte que ensembleArcValués ne contienne que des ArcsValue
private static final long serialVersionUID = -7163498825360866323L;
}
And you'll need this one to :
public class EnsembleSommet<S> extends Ensemble<Sommet<S>>
{
public EnsembleSommet()
{
super();
}
public EnsembleSommet(EnsembleSommet<S> ensemble)
{
super(ensemble);
}
private static final long serialVersionUID = 7278825382690341067L;
#Override
public EnsembleSommet<S> clone ()
{
return (EnsembleSommet<S>)super.clone();
}
public Sommet<S> firstSommet()
{
#SuppressWarnings("unchecked")
Sommet<S>[] tab=new Sommet[size()];
return toArray(tab)[0];
}
}
The only way you can achieve this is to make the type of Arc you want part of your generic deceleration. Rename your existing EnsembleArc to AbstractEnsembleArc and change it's generic decleration from < S > to < S, T extends Arc< S > > i.e.:
public abstract class AbstractEnsembleArc<S, T extends Arc<S>> extends Ensemble<T> {
// PUT ALL YOUR LOGIC CURRENTLY IN EnsembleArc HERE
}
Now create a new Class Called EnsembleArc and extend the new abstract class you've added, this new class will work identically to your existing EnsembleArc and class decleration should now look like:
public class EnsembleArc<S> extends AbstractEnsembleArc<S, Arc<S>> {
}
Finally have EnsembleArcValues extend the Abstract class instead of EnsembleArc so that you can declare that it should only accepts ArcValue and not simple Arc, do that like this:
public class EnsembleArcValues<S, V> extends AbstractEnsembleArc<S, ArcValue<S, V>> {
}
I have the following class:
public class RefactorMe {
private static List<Event<Apple>> mAppleEventList = new ArrayList<Event<Apple>>();
private static List<Event<Banana>> mBananaEventList = new ArrayList<Event<Banana>>();
private static List<Event<Orange>> mOrangeEventList = new ArrayList<Event<Orange>>();
public static List<Event<Apple>> getAppleList() {
return mAppleEventList;
}
public static List<Event<Banana>> getBananaEventList() {
return mBananaEventList;
}
public static List<Event<Orange> getOrangeList() {
return mOrangeEventList;
}
public static void addAppleEvent(Event<Apple> pEvent) {
mAppleEventList.add(pEvent);
}
public static void addBananaEvent(Event<Banana> pEvent) {
mBananaEventList.add(pEvent);
}
public static void addOrangeEvent(Event<Orange> pEvent) {
mOrangeEventList.add(pEvent);
}
}
I tried refactoring it using the Visitor pattern but could not get it to work because of the generics.. Is there a better way to do this?
Following on #user902383 by using the Map here is a solution for you in Java 7:
public class RefactorMe {
class Event<K> {
public K getNewObject() {
return null;
}
}
private static Map<Class<?>, List<Event<?>>> eventLists = new HashMap<>();
public static <E> List<Event<E>> getEventList(Class<E> clazz) {
return (List) eventLists.get(clazz);
}
public static <E extends Event<E>> void addEvent(Event<E> pEvent) {
Class<E> key = (Class<E>) pEvent.getNewObject().getClass();
List<Event<?>> events = eventLists.get(key);
if (events == null) {
events = new ArrayList<>();
eventLists.put(key, events);
}
events.add(pEvent);
}
}
MyMath's constructor is supposed to call Homework's constructor, but super(); returns an error 'cannot find symbol'. It should not have any arguments.
Also, I am confused about how to call the method createAssignment using an arraylist, but I have to use it. Any advice?
Homework
public abstract class Homework {
private int pagesToRead;
private String typeHomework;
public Homework(int pages, String hw) {
// initialise instance variables
pagesToRead = 0;
typeHomework = "none";
}
public abstract void createAssignment(int p);
public int getPages() {
return pagesToRead;
}
public void setPagesToRead(int p) {
pagesToRead = p;
}
public String getTypeHomework() {
return typeHomework;
}
public void setTypeHomework(String hw) {
typeHomework = hw;
}
}
MyMath
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath() {
super();
}
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
public String toString() {
return typeHomework + " - " + pagesRead;
}
}
public class testHomework {
public static void main(String[] args) {
ArrayList<Homework> list = new ArrayList<Homework>();
list.add(new MyMath(1));
list.add(new MyJava(1));
for (Homework s : list) {
s.createAssignment();
}
}
}
Compiler error:
Regarding the compiler error, you have to change the MyMath constractor to somthing like:
public MyMath() {
super(someInt, someString);
}
Or, you can add a non-arg constructor to the Homework class:
public Homework() {
this(someInt,someString);
}
You can learn about the super() keyword in the Javadocs tutoriel:
If a constructor does not explicitly invoke a superclass constructor,
the Java compiler automatically inserts a call to the no-argument
constructor of the superclass. If the super class does not have a
no-argument constructor, you will get a compile-time error. Object
does have such a constructor, so if Object is the only superclass,
there is no problem.
Code Suggestion:
As there is many other issues in your question, i modified all your classes like below:
Homework.java:
public abstract class Homework {
private int pagesToRead;
private String typeHomework;
{
// initialise instance variables
pagesToRead = 0;
typeHomework = "none";
}
public Homework(int pages, String hw) {
this.pagesToRead = pages;
this.typeHomework = hw;
}
public abstract void createAssignment(int p);
public int getPages() {
return pagesToRead;
}
public void setPagesToRead(int p) {
pagesToRead = p;
}
public String getTypeHomework() {
return typeHomework;
}
public void setTypeHomework(String hw) {
typeHomework = hw;
}
}
MyMath.java
public class MyMath extends Homework {
private int pagesRead;
private String typeHomework;
public MyMath(int pages, String hw) {
super(pages,hw);
}
public void createAssignment(int p) {
setTypeHomework("Math");
setPagesToRead(p);
}
public String toString() {
return typeHomework + " - " + pagesRead;
}
}
TestHomework.java:
class TestHomework {
public static void main(String[] args) {
ArrayList<Homework> list = new ArrayList<Homework>();
// will create a homework with type Math and one page to read
list.add(new MyMath(1,"Math"));
// Assuming MyJava is similar to MyMath
list.add(new MyJava(1,"Java"));
for (Homework s : list) {
if (s instanceof MyMath) {
// modify the number of pages to read for the Math homework
s.createAssignment(3);
} else if (s instanceof MyJava) {
// modify the number of pages to read for the Java homework
s.createAssignment(5);
} else {
s.createAssignment(7);
}
}
}
}
I'm reading "Design Pattern for Dummies". I read and practiced Decorator Pattern. With Decorator Pattern, we can decorate an object with anything. Now, I want to remove decorated object before decorated.I have solved this problem by an ArrayList but I still feel it's not good. Can you tell me how to remove a decorated object? And what is a better way?
this is my way:
Computer.java
public class Computer {
public Computer() {
}
public String description() {
return "computer";
}
}
ComponentDecorator.java
public abstract class ComponentDecorator extends Computer {
#Override
public abstract String description();
}
CD.java
public class CD extends ComponentDecorator {
private Computer computer;
public CD() {
}
public CD(Computer computer) {
this.computer = computer;
}
#Override
public String description() {
return computer.description() + " and a CD";
}
}
Disk.java
public class Disk extends ComponentDecorator {
private Computer computer;
public Disk() {
}
public Disk(Computer c) {
computer = c;
}
#Override
public String description() {
return computer.description() + " and a disk";
}
}
Monitor.java
public class Monitor extends ComponentDecorator {
private Computer computer;
public Monitor() {
}
public Monitor(Computer computer) {
this.computer = computer;
}
#Override
public String description() {
return computer.description() + " and a monitor";
}
}
Main.java
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
static ArrayList<ComponentDecorator> list = new ArrayList<>();
public static void main(String[] args) {
addComponent(new CD(), new Disk(), new Monitor());
System.out.println(list.size());
Computer penIII = getComputer();
removeComponent(new Monitor());
penIII = getComputer();
System.out.println(penIII.description());
}
private static void addComponent(ComponentDecorator... comp) {
list.addAll(Arrays.asList(comp));
}
private static void removeComponent(ComponentDecorator comp) {
for(ComponentDecorator c : list) {
if(c.getClass() == comp.getClass()) {
list.remove(list.indexOf(c));
break;
}
}
}
private static Computer getComputer() {
Computer c = new Computer();
Class e;
for(ComponentDecorator d : list) {
e = d.getClass();
try {
c = (Computer) e.getConstructor(new Class[]{Computer.class}).newInstance(c);
} catch(Exception ex) {
ex.printStackTrace();
}
}
return c;
}
}
A nicer way would be adding the "removeDecorator" method to your ComponentDecorator class.
public abstract class ComponentDecorator {
private ComponentDecorator subject;
public ComponentDecorator(ComponentDecorator subject) {
this.subject = subject;
}
#Override
public abstract String description();
}
public void removeDecorator(ComponentDecorator toRemove) {
if (subject == null) {
return;
} else if (subject.equals(toRemove)) {
subject = subject.getSubject();
} else {
subject.removeDecorator(toRemove);
}
}
public ComponentDecorator getSubject() {
return subject;
}
// Computer
public class Computer extends ComponentDecorator{
public Computer() {
super(null);
}
public String description() {
return "computer";
}
// CD
public class CD extends ComponentDecorator {
public CD(ComponentDecorator computer) {
super(computer);
}
#Override
public String description() {
return getSubject().description() + " and a CD";
}
}
// main
public static void main(String[] args) {
ComponentDecorator penIII = new Computer();
penIII = new CD(penIII);
penIII = new Monitor(penIII);
System.out.println(penIII.description());
}
}
If you don't have the reference of the decorator to remove, you can create another method that the a Class instead.
You'll need to the decorated object as "ComponentDecorator" instead of "Computer" however. I suggest to make the Computer class extends ComponentDecorator instead of the other way around.
I suspect I'm misunderstanding your question, but to get the decorated (inner) object out of the decorator, you can just add a get method to the decorators. Add
public abstract Computer getDecorated();
to ComponentDecorator and
public Computer getDecorated(){return computer;}
to each subclass (CD, Monitor, ...). Is that what you were looking for?
Add two methods to an interface, undecorate() and removeDecoration(String className):
ThingInterface.java
public interface ThingInterface {
public ThingInterface undecorate();
public ThingInterface removeDecoration(String className);
public String nonDecoratedString();
public String decoratedString();
}
Your base class will simply return itself for those methods:
BaseThing.java
public class BaseThing implements ThingInterface {
private String basicString;
public BaseThing(String string) {
basicString = string;
}
#Override
public ThingInterface undecorate() {
return this;
}
#Override
public ThingInterface removeDecoration(String className) {
return this;
}
#Override
public String nonDecoratedString() {
return basicString;
}
#Override
public String decoratedString() {
return basicString;
}
}
Now the real meat of what you need is in the abstract class:
AbstractThingDecorator.java
public abstract class AbstractThingDecorator implements ThingInterface {
private ThingInterface thing;
public AbstractThingDecorator(ThingInterface thing) {
this.thing = thing;
}
#Override
public ThingInterface removeDecoration(String className) {
ThingInterface undecorate = this;
if(this.getClass().getName() == className) {
undecorate = this.undecorate();
}
else {
ArrayList<String> classStack = new ArrayList();
while(undecorate != undecorate.undecorate()) {
if(undecorate.getClass().getName() != className) {
classStack.add(undecorate.getClass().getName());
}
undecorate = undecorate.undecorate();
}
for(int i = classStack.size()-1;i == 0;i--) {
try {
Class<?> clazz = Class.forName(classStack.get(i));
Constructor<?> ctor = clazz.getConstructor(ThingInterface.class);
Object object = ctor.newInstance(new Object[] { undecorate });
undecorate = (ThingInterface) object;
}
catch(Exception e) {
System.out.println("Exception:" + e.getMessage());
}
}
}
return undecorate;
}
#Override
public ThingInterface undecorate() {
return this.thing;
}
#Override
public String nonDecoratedString() {
return thing.nonDecoratedString();
}
#Override
public String decoratedString() {
return thing.decoratedString();
}
}
I'm adding two simple decorators, ThingDecorator and FancyThingDecorator:
ThingDecorator.java
public class ThingDecorator extends AbstractThingDecorator {
public ThingDecorator(ThingInterface thing) {
super(thing);
}
#Override
public ThingInterface undecorate() {
return super.undecorate();
}
#Override
public String decoratedString() {
return super.decoratedString() + ", decorated";
}
}
FancyThingDecorator.java
public class FancyThingDecorator extends AbstractThingDecorator {
public FancyThingDecorator(ThingInterface thing) {
super(thing);
}
#Override
public ThingInterface undecorate() {
return super.undecorate();
}
#Override
public String decoratedString() {
return super.decoratedString() + ", fancy";
}
}
Finally, my java main:
Decorator.java
public class Decorator {
/**
* #param args
*/
public static void main(String[] args) {
ThingInterface thing = new BaseThing("Basic string");
ThingInterface decorator = new ThingDecorator(thing);
ThingInterface fancyDecorator = new FancyThingDecorator(thing);
ThingInterface extraFancy = new FancyThingDecorator(new ThingDecorator(thing));
ThingInterface undecorate = new FancyThingDecorator(new ThingDecorator(thing));
System.out.println("Basic thing is: " + thing.decoratedString()+".");
System.out.println("Decorated thing is: " + decorator.decoratedString()+".");
System.out.println("Fancy thing is: " + fancyDecorator.decoratedString()+".");
System.out.println("Decorated fancy thing is: " + extraFancy.decoratedString()+".");
while(extraFancy.undecorate() != extraFancy) {
extraFancy = extraFancy.undecorate();
System.out.println("Rolling back decorations: " + extraFancy.decoratedString()+".");
}
System.out.println("Decoration chain before removal is: " + undecorate.decoratedString());
System.out.println("Removing decoration for " + ThingDecorator.class.getName());
undecorate = undecorate.removeDecoration(ThingDecorator.class.getName());
System.out.println("Decoration chain after removal is: " + undecorate.decoratedString()+".");
}
}
The output is:
Basic thing is: Basic string.
Decorated thing is: Basic string, decorated.
Fancy thing is: Basic string, fancy.
Decorated fancy thing is: Basic string, decorated, fancy.
Rolling back decorations: Basic string, decorated.
Rolling back decorations: Basic string.
Decoration chain before removal is: Basic string, decorated, fancy
Removing decoration for ThingDecorator
Decoration chain after removal is: Basic string, fancy.