-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?

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

That was fast! Thanks for an informative and quick solution. :)
No problem. If you think the issue's adequately solved, you can consider accepting my answer. 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.)
I was going to, i dont think i can accept an answer until 10 minutes have passed. Thanks again :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.