File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics" Watch "Generics" New topic
Author

Generics

Jeroen Wolff
Greenhorn

Joined: Jun 26, 2007
Posts: 4
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
internet detective
Marshal

Joined: May 26, 2003
Posts: 29220
    
135

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.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Jeroen Wolff
Greenhorn

Joined: Jun 26, 2007
Posts: 4
Thanks...but where do i get 'type' variable from in the create() method?

Regards,

Jeroen
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13868
    
  10

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?


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics
 
Similar Threads
generics
Generics
Generics Confusion
Generics
generics