javaarraysclassexceptiontoarray

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Class;


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;
  }

Solution

  • 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);