Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

java - How to pass argument that implements a interface?

I have a interface:

public interface InterfaceX {
    void methodX();
}

A class that have a method to receive a object that implements that interface:

public class AClass {
    public <T extends InterfaceX>  void Method( Class<T> argument ) {
        // ....
    }
}

And a class that implements the interface and wants to call the above method..

public class BClass implements InterfaceX {
    @Override
    public void methodX() {
    }

    public void callAClassMethod() {
        AClass aClass = new AClass();
        aClass.Method(this);
    }
}

How to do this? In this code I have the error:

no instance(s) of type variable(s) T exist so that BClass conforms to Class<T>

question from:https://stackoverflow.com/questions/65865858/how-to-pass-argument-that-implements-a-interface

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Didn't test this, but if you want the class type, you have to call getClass().

public class BClass implements InterfaceX {
    @Override
    public void methodX() {
    }

    public void callAClassMethod() {
        AClass aClass = new AClass();
        aClass.Method(this.getClass());
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...