-3

when I'm executing the below code I'm getting Class cast exception. I believe in an object is trying to cast with class can anyone help me

 public abstract AGridFilterMenu refreshFilters();


 public AGridFilterMenu supportFilter(String style, Class<? extends AFilterItem> clazz, By... childLocators) {
      ArrayList<Class<By>> signature = new ArrayList<>();
      for(int i = 0; i< childLocators.length; i++) {
          signature.add(By.class);
      }

      try {
        Constructor<? extends AFilterItem> construct = clazz.getConstructor((Class<?>[]) signature.toArray());
        constructors.put(style, construct);
        filteritemChildLocators.put(style, childLocators);
    } catch (NoSuchMethodException | SecurityException e) {
        throw new TestCodeException("Unsupported FilterItem signature", e);
    }
      return this;
  }

  public AFilterItem getFilter(String filterName) {
    logger.trace(String.format("Retrieving filter %s", filterName));
    AFilterItem item = filters.get(filterName);`enter code here`
    item.bind();
    return item;
  }
diziaq
  • 6,881
  • 16
  • 54
  • 96
Ram
  • 23
  • 1
  • 4

1 Answers1

1

The problem is method Object[] List.toArray() returns an array of Object and it cannot be cast to array of Class<?>.

Luckily, there's a more suitable method T[] List.toArray(T[]), but you need to prepare an array instance of particular size and type to store the result.

Keep in mind that in case of ArrayList both argument and returning value are the same instance of array, which is mutating inside the toArray method.

Class<?>[] signatureArray = new Class<?>[signature.size()];
signature.toArray(signatureArray);
Constructor<? extends AFilterItem> construct = clazz.getConstructor(signatureArray);
diziaq
  • 6,881
  • 16
  • 54
  • 96
  • You do not have to prepare a size matching array. It's just better performance, because a size matching array is used directly. Otherwise, a size matching array is created. I use either a constant zero sized array or indeed a new size matching array. – jokster Jul 31 '18 at 07:58
  • @jokster, you're right - the precise contract of the method is in javadoc. – diziaq Jul 31 '18 at 13:44