[java] Problems with Array class ...
Hello.
How can I create an object of Array class. This is an error:
Array arr = new Array(); //Array has private access in java.lang.reflect.Array
The Array class provides helper functions to work with arrays. This class is not meant to be instantiated.
To create a new array of a type, say char, write this:
char[] myArray = new char[4711];
Then you can use it in another function like this:
... func(Object[] array) throws IllegalArgumentException
{
char c = java.lang.reflect.Array.getChar(array, 3);
...
}
To create a new array of a type, say char, write this:
char[] myArray = new char[4711];
Then you can use it in another function like this:
... func(Object[] array) throws IllegalArgumentException
{
char c = java.lang.reflect.Array.getChar(array, 3);
...
}
Quote:Original post by nmi
The Array class provides helper functions to work with arrays, since arrays don't provide them.
To create a new array of a type, say char, write this:
char[] myArray = new char[4711];
I'm sorry, but you are wrong. You can create Array class object. Its suppost to be an universal array wich is working with all kinds of objects and primitive types.
There is a method for creatig Array class object, but I cant figure out how it works : Array.newInstance(Class type, int length)
The problem is that I get Class type, and my method must return Array type.
So I tried: return (Array)arr; //inconvertability !!!
Quote:Original post by cpp_boy
I'm sorry, but you are wrong. You can create Array class object. Its suppost to be an universal array wich is working with all kinds of objects and primitive types.
There is a method for creatig Array class object, but I cant figure out how it works : Array.newInstance(Class type, int length)
The constructor of Array is private, so you cannot instanciate the class Array. Its also not supposed to be an universal array, since Object[] does this job. (You can put integral types like int or char into an Object[] by using java.lang.Integer, etc.)
The method newInstance can be used to create arrays of an unknown type.
So instead of writing
String[] myArray = new String[4711];
you could write
String[] myArray = Array.newInstance(String.class, 4711);
That also works if the function accepts the type as parameter:
public Object createArray(Class componentType)
{
return Array.newInstance(componentType, 4711);
}
Then use it like this:
String[] myStrings = (String[])createArray(String.class);
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement