4

What I want to do is add an generic interface to several classes that allows them to call a static load method to instantiate objects with information from a database. This should allow them to be used in other generics class, in my case a ListModel for "LoadAble" classes.

Problems:

  1. One has to define static methods inside the interface
  2. One can not override static interface methods in implementing classes
  3. One has to instantiate an object before calling non static methods
  4. Generic types require deceleration for calling the needed method.
  5. Abstract classes don't support static methods.

2 Answers 2

3

static methods cannot implement an interface method.

What you're looking for is the Factory Pattern, i.e. an interface with a "create" method, and multiple implementations (factories).

You can implement the factory as a static nested class, if you want to keep that logic together:

public interface Factory { public Object create(); } public class MyClass { public static class MyFactory implements Factory { @Override public Object create() { return new MyClass(); } } private MyClass() { } } 

Now you can use it:

Factory factory = new MyClass.MyFactory(); Object obj = factory.create(); 
Sign up to request clarification or add additional context in comments.

Comments

1

The solution is a dummy object created in the interface

public interface LoadAble<T> { public static <T extends LoadAble<T>> LinkedList<T> loadThis(Class<T> c) { try { T t = c.newInstance(); return t.loadAll(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } return null; } public LinkedList<T> loadAll(); } 

This can now be called with

LoadAble.loadThis(LoadAbleClass.class); 

I hope this will help someone who has the same problem I had, maybe someone can suggest a better method though.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.