File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics

 
Jeroen Wolff
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please can somebody help me to make this generics work....
Ik would like to create a new object for a class that is a generic parameter.
A new instance of the <T> class.....how to do??

Thanks!!

Regards,

Jeroen


ServiceImpl<WhatEver> service = new ServiceImpl<WhatEver>();
PersistentObject w = service.create();




public abstract class PersistentObject {
private Long OID;
}


public class WhatEver extends PersistentObject {
public WhatEver() {
super();
}
}

public interface IService<T extends PersistentObject> {
public T create();
}


public class ServiceImpl<T extends PersistentObject> implements IService<T> {

public T create() {
return ??? newInstance();
}
}
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 33691
316
Eclipse IDE Java VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jeroen Wolff:
A new instance of the <T> class.....how to do??

Awkwardly. The following is the simplest way i can think of:


It gets the class to create a new object and then casts it back to the requested type.
 
Jeroen Wolff
Greenhorn
Posts: 4
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks...but where do i get 'type' variable from in the create() method?

Regards,

Jeroen
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot do this without passing the type explicitly: see Angelika Langer's Java Generics FAQ - Can I create an object whose type is a type parameter?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic