Is it possible to obtain a reference/pointer to a class type and enforce that it derives from a particular base class?
I’m writing a client library that needs to negotiate with a server to pick an algorithm to use for communication. I want the user of the library to be able to select a subset of algorithms to use and not be fixed to the set I initially provide (ie. not fixed in some kind of factory class).
Ideally this would be done by passing in a list of classes that derive from some common “Algorithm” subtype. I’ve seen the “Type” object but I would have to check all the types myself. Is there a way to have the compiler do this for me? What I want is something like “Type<Algorithm>” but I can’t find anything like that. Or is there different way entirely to do this?
An example of what I’ve thought of so far:
public class Algorithm {
public static abstract Name;
}
public class Client {
public MyLib(Type[] algorithms) {
m_algorithms = algorithms;
// ... Check they all derive from Algorithm
}
public Communicate() {
// ... Send list of algorithm names to server
// ... Create instance of algorithm dictated by server response
}
}
You unfortunately can’t check that the types are all Algorithms at compile time. This is one of the (few) features I miss about Java. However, there are some good workarounds, which (depending on your situation) may be better than the solution you were hoping for. For example:
Then you can use your client class like this: