1

I frequently write code where I say

public class MyClass
{
  public static MyClass makeOne(some parameters) {
    MyClass mc=new MyClass();
    ... various manipulations to populate the class ...
  }
  ... etc ...
}

But then I may subtype this class, or cut-and-paste the code to another class, and if so I have to change all the occurrences of the class name to the new class.

What I'd really like to do is something like

public class MyClass
{
  public static <T> makeOne {
    <T> one=new <T>();
    ... various manipulation to populate the class ...
  }
... etc ...
}

I'm using the notation of generics (sort of), but I don't mean to imply that it can be done with generics or that it would look anything like that.

Is there a way to do this?

Jay
  • 26,876
  • 10
  • 61
  • 112
  • There is not. There are [tricks](https://stackoverflow.com/questions/936684/getting-the-class-name-from-a-static-method-in-java) to get the `Class` object for the enclosing class but that's about it. Be explicit. – Sotirios Delimanolis Apr 05 '19 at 01:29
  • Maybe I misunderstood the problem , but why dont you just pass Class to method and create an instance on it? public class MyClass { public static T makeOne(Class clazz) throws InstantiationException, IllegalAccessException { T instance = clazz.newInstance(); //populate return instance; } } – beatrice Apr 05 '19 at 08:36
  • Because it sounds like object construction is an important aspect of your requirements, you should consider implementing the Factory pattern or the Builder pattern instead of giving that responsibility to the classes in your inheritance hierarchy. – RWRkeSBZ Apr 05 '19 at 18:49

0 Answers0