Ask coding questions

← Back to all posts
Java unity like getComponent method
OmN3xin (48)

Hello,
I would like to know is how to have a method public Component getComponent(Class type);
and for it to return a Component from a list: List<Component> components = new ArrayList<>();. (already added this) When you add a Component to the list, it is a class extending from Component.

Answered by EpicGamer007 (1736) [earned 5 cycles]
View Answer
Comments
hotnewtop
EpicGamer007 (1736)

can you clarify a bit more? What is your goal? Are you trying to make an ArrayList which ONLY accepts subclasses of Component? If that is your goal, it is pretty simple. Make the List be List<? extends Component> components = new ArrayList(); or you could make a method like

public <T extends Component> void addComponent(List<T> list) {

}

If you want to make a method which accepts any animal or animal subclass, you can also do this

public void addComponent(List<Component> l) {
}

I do not remember a lot about Java generics so if I misinterpreted your question or my code does not work, please let me know.

OmN3xin (48)

@EpicGamer007 My goal is for the user to pass in a class in the method(I would prefer generics), then for the method to find the item from the list with the type passed in, then return that instance.

EpicGamer007 (1736)

@OmN3xin First, you need to find a way to pass a class. Take a look at this SO question: https://stackoverflow.com/questions/4872978/how-do-i-pass-a-class-as-a-parameter-in-java

After that, its pretty simple

public Object getByClassName(Class c) {

  for(Object a: objectList) {
    if(a instanceof c) {
      return a;
    }
  }

  return null

}

something like this should work

OmN3xin (48)

@EpicGamer007 Thank you, this helped.