File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics" Watch "Generics" New topic


Jeroen Wolff

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> to do??




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

public abstract class PersistentObject {
private Long OID;

public class WhatEver extends PersistentObject {
public WhatEver() {

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

Joined: May 26, 2003
Posts: 33130

Originally posted by Jeroen Wolff:
A new instance of the <T> 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.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Jeroen Wolff

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


Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15094

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 8 API documentation
I agree. Here's the link:
subject: Generics
It's not a secret anymore!