-1

So, the title sais everything. When i try to pass arguments in an Object array using .newInstance i get an error:

java.lang.IllegalArgumentException: argument type mismatch at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at me.voxed.textrpg.RoomCreator.setNorth(RoomCreator.java:44) at me.voxed.textrpg.Game.(Game.java:89) at me.voxed.textrpg.Program.main(Program.java:6)

This is the function im using:

    public void setNorth(String block, String... args){
    try {
        Object[] argsObj = args;
        Class<? extends Block> clazz = (Class<? extends Block>) (GameRegistry.getBlock(block));
        _north = clazz.asSubclass(Block.class).getConstructor(Object[].class).newInstance(argsObj);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
            | NoSuchMethodException | SecurityException e) {
        e.printStackTrace();
    }
}

And clazz is this class:

public class BlockNPCSpawnBars extends BlockNPC {

public BlockNPCSpawnBars(Object[] args) {
    super(args);
}

What am i doing wrong?

Voxed
  • 31
  • 7

1 Answers1

2

newInstance takes variable arguments. When you pass it an array, it translates to a varargs call, as if each element in that array were a separate argument to the constructor.

This is generally solved like the following:

...newInstance((Object) argsObj);

That will ensure the array is passed as the singular argument, like your actual constructor is expecting.

Radiodef
  • 37,180
  • 14
  • 90
  • 125
  • That was fast! Thanks for an informative and quick solution. :) – Voxed Nov 21 '15 at 16:10
  • No problem. If you think the issue's adequately solved, you can consider accepting my answer. http://meta.stackexchange.com/q/5234/244864 Also, note that the explicit `(Object)` cast is basically just a shorthand for the code shown in the link from @luanjot. (Varargs sees the `Object` and creates an array around it with 1 element.) – Radiodef Nov 21 '15 at 16:12
  • 1
    I was going to, i dont think i can accept an answer until 10 minutes have passed. Thanks again :) – Voxed Nov 21 '15 at 16:15