There is a class in this form. Ie to write Foo or Bar with the indication of import will not work, just like that.

 Class foo = Class.forName("com.secret.Foo"); Class bar = Class.forName("com.secret.Bar"); 

There is a method in the Foo class called make . He needs to pass an array of Bar classes. How to implement this?

If you could use these classes

 Bar bar1 = new Bar(1); Bar bar2 = new Bar(2); Bar[] bars = {bar1, bar2}; Foo.make(bars); 

What about reflection?

UPD

Tried to do so

 ArrayList<Object> ar = new ArrayList<>(); ar.add(bar1); ar.add(bar2); Class foo = Class.forName("com.secret.Foo"); for(Method m : foo.getMethods()){ if(m.getName().equals("make")) { m.invoke(foo, new Object[]{ar.toArray()}); } } 

But this way I get an error

 java.lang.IllegalArgumentException: method com.secret.Foo.make argument 1 has type com.secret.Bar[], got java.lang.Object[] 

    1 answer 1

    Suppose the Bar class looks like this:

     package com.secret; class Bar { protected final int value; protected Bar(int value) { this.value = value; } } 

    A class Foo - so:

     package com.secret; class Foo { protected static void make(Bar[] bars) { for (Bar bar : bars) { System.out.println("Making bar: " + bar.value); } } } 

    Then from the outside (taking into account the access modifier protected by the constructor and method), you can do it like this:

     package test; import java.lang.reflect.*; public class Test { public static void main(String[] args) { try { Class foo = Class.forName("com.secret.Foo"); Class bar = Class.forName("com.secret.Bar"); Constructor constr = bar.getDeclaredConstructor(int.class); constr.setAccessible(true); Object bar1 = constr.newInstance(1); Object bar2 = constr.newInstance(2); Object array = Array.newInstance(bar, 2); Array.set(array, 0, bar1); Array.set(array, 1, bar2); Method method = foo.getDeclaredMethod("make", array.getClass()); method.setAccessible(true); method.invoke(null, new Object[] { array }); } catch (Exception e) { e.printStackTrace(); } } } 

    Output on display:

     Making bar: 1 Making bar: 2 
    • Wow, cool! I found something on enSO, but did not go beyond creating the array. I did not understand how to use Array . Thanks :) - Flippy