I am currently attempting to write a method which returns a new array of a generic type filled with objects of random values but I am struggling with the creation of the Objects.
Let's say I have a class Rectangle and a class Cricle which both can only be initialised by their constructor and lack an empty constructor. Is it possible to access the constructor of those example classes when working with a generic method?
Rectangle.java
public class Rectangle
{
private double width;
private double height;
private double area;
public Rectangle( double width, double height )
{
this.width = width;
this.height = height;
this.area = width * height;
}
// Getter....
}
Circle.java
public class Circle
{
private double area;
private double radius;
public Circle( double radius )
{
this.radius = radius;
this.area = Math.PI * Math.pow( radius, 2 );
}
// Getter....
}
What I hoped could work out somehow:
ArrayFactory.java
public class ArrayFactory<T>
{
@SuppressWarnings ( "unchecked")
public T[] getArray( int size, int min, int max )
{
Random ran = new Random();
double var1 = (ran.nextDouble() * max) - min;
double var2 = (ran.nextDouble() * max) - min;
T[] temp = (T[]) new Object[size];
for ( int i = 0; i < t.length; i++ )
{
// this does obviously not work
// because the constructor of java.lang.Object takes no arguments
temp[ i ] = (T) new Object(var1,var2);
}
return temp;
}
}