Reputation: 71
Honestly, I'm not sure the title fits this correctly; But I will try to explain my problem with examples.
Say I have two classes
public class Entity {
private static int lastID = 0;
private int ID;
private Entity(){};
public static Entity create(){
lastID++;
Entity ent = new Entity();
ent.ID = lastID;
return ent;
}
}
public class Blob extends Entity {
private int x,y;
pubic void setPos(int X,int Y){;
x = X;
y = Y;
}
}
The way I'd like to interface with the Entity factory would be in the form of
Blob b = Entity.create<Blob>();
Or something in that nature.
My best attempt was
public static <E extends Entity> E create(){
E ent = new E();
...
but that doesn't want to work.
Upvotes: 0
Views: 103
Reputation: 1873
I am afraid it can't be done without actually passing a class or its name as an argument.
You can then use a generic construction <E extends Entity<E>>
to make it typesafe and avoid manual type casting.
public class Entity<E extends Entity<E>> {
private static int lastID = 0;
protected int ID;
protected Entity() {
}
public static <E extends Entity<E>> E create(Class<E> clazz) {
lastID++;
E newItem;
try {
newItem = clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e); // let's hope your child classes will have a working default constructor
}
newItem.ID = lastID;
return newItem;
}
public int getID() {
return ID;
}
}
public class Blob extends Entity<Blob> {
private int x,y;
public Blob() {
}
public void setPos(int X,int Y){;
x = X;
y = Y;
}
}
public class AnotherBlob extends Entity<AnotherBlob> {
String help = "Help!";
public String help() {
return help;
}
}
// TEST!
public class Test {
public static void main(String[] args) {
Blob blob = Entity.create(Blob.class);
AnotherBlob anotherBlob = Entity.create(AnotherBlob.class);
System.out.println("Blob: " + blob.getClass() + " ID = " + blob.getID() +
"\nAnother blob: " + anotherBlob.getClass() + " ID = " + anotherBlob.getID());
}
}
Upvotes: 1
Reputation: 1506
A simple factory method might look something like this. Keep it in its own class (not in Entity class) and have the name Factory someplace in name so it has context
public static final Entity getInstance(String id){
Entity instance = null;
if(id.equals("Blob")) {
instance = new Blob();
}
else if(id.equals("Another Blob")) {
instance = new AnotherBlob();
}
// more Entity types here
return instance;
}
Upvotes: 1