简体   繁体   中英

How can I create an instance of a class implementing an interface from a method?

I have the following probem.
I have these Java classes:

class A {
    B makeB() {
        return new B();
    }
}

class B implements X {
    // X methods implementations (plus other methods)
}

interface X {
    // methods declarations
}

For testing purposes, I need to modify the method makeB so that it can create a new instance of every class that implements the X interface.

I tried with generics:

class A<T extends X> {
    X makeB() {
        return new T();
    }
}

but this code isn't correct. I also tried in the following way:

class A {
    X makeB() {
        return X.createInstance();
    }
}

class B implements X {
    @Override
    public static X createInstance() {
        return new B();
    }
    // X methods implementations (plus other methods)
}

interface X {
    static X createInstance() {}
    // other methods declarations
}

but Java doesn't support overriding of static methods.

How can I change makeB so that it behaves as I want (if there is a way to do so)?

(Neither the title neither the description of my question are very clear, the problem is that I can't find a way to say it better. My apologies.)

Thanks to everyone who will answer.

Look at Mockito a unit test framework which allow you to mock (override/redefine) method implementations.

Also have a look to the dependency injection pattern which help to solve issues like this one.

Generics might be a better way to go. Your generic's code is syntactically incorrect. Try this:

class A<T extends X> {
    T makeB() {
        return new T();
    }
}

Source: https://docs.oracle.com/javase/tutorial/java/generics/types.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM