-2

I would like to pass a class as a parameter in java. How do I pass a class as a parameter in Java?

that's the thing I found with answers, but doing it that way doesn't do what I want to.

what I want to do is something like this:

public List<cls> getTouchingObjects(Class cls){
    List<cls> thing;
    //fill thing
    return thing;
}

it doesn't exactly work though... any idea how I could get this to work?

Elijah S
  • 7
  • 6
  • You can't do what you want due to Java generics type erasure. Looks like an [XY Problem](http://xyproblem.info/) type question regardless. Please consider telling us *why* you want to do this, what overall problem you're trying to solve. You know that generic constants are mainly used for compile-time type safety, and your code is trying to shoehorn this into the run-time world. – Hovercraft Full Of Eels Apr 02 '18 at 19:05
  • 1
    Do you really want a `Class` object, or do you want an instance of an object? They are two *very* different things. – Makoto Apr 02 '18 at 19:05
  • It is really difficult to understand what you want to achieve yet the answer from @bowmore seems to be matching best to what you might want – Oleg Sklyar Apr 02 '18 at 19:10
  • Yes @Oleg, his solution did work I believe I marked that as such, but if I didn't, it would be nice to know how to do so. Sorry about it not being very specific. – Elijah S Apr 19 '18 at 12:52

1 Answers1

0

The Class class takes a generic parameter. So rather than passing Class cls, pass Class<T> cls.

public <T> List<T> getTouchingObjects(Class<T> cls){
    List<T> thing;
    //fill thing
    return thing;
}

This allows you to specify the return type, in terms of the class passed as a parameter. The implementation, will still most likely be using introspection.

Of course as it is this can still allow clients to pass a class that is nonsensical to your context. I guess whatever your method does, it won't be applicable to Strings, yet nothing prevents calling getTouchingObjects(String.class). You haven't specified what type those touching objects have generally, but for the sake of example I'll assume they ought to be subclasses of ChessPiece. In that case you'd narrow the method down like this :

public <T extends ChessPiece> List<T> getTouchingObjects(Class<T> cls){
    List<T> thing;
    //fill thing
    return thing;
}

Like that, calling getTouchingObjects(String.class) won't even compile, and you've improved your type safety even more.

bowmore
  • 10,842
  • 1
  • 35
  • 43
  • 1
    Why even have a `cls` parameter for this code or any method parameter at all? It's not needed, not used, and the only purpose it serves is to confuse. – Hovercraft Full Of Eels Apr 02 '18 at 19:10
  • @HovercraftFullOfEels not really useless. Client code can avoid casting by passing the class it expects. It's the implemntation's job to make sure it's type safe. – bowmore Apr 02 '18 at 19:13