[英]How can I initialize a generic variable in Java?
我正在嘗試編寫一個方法,其中我需要創建一個通用類型T的臨時變量sum。但是,我收到錯誤“局部變量sum可能尚未初始化”。 如何初始化通用變量? 我無法將其設置為0或0.0,我無法在任何地方找到有關如何處理此信息的信息。 以下是我正在使用的代碼部分:
public Matrix<T,A> multiply(Matrix<T,A> right) throws MatrixException
{
Matrix<T,A> temp = new Matrix<T,A>(arithmetics, rowSize, columnSize);
T sum, product;
if (rowSize != right.columnSize)
throw new MatrixException("Row size of first matrix must match column size "
+ "of second matrix to multiply");
setup(temp,rowSize,columnSize);
for (int i = 0; i < rowSize; i++){
for (int j = 0; j < right.columnSize; j++) {
product = (arithmetics.multiply(matrix[i][j] , right.matrix[j][i]));
sum = arithmetics.add(product, sum);
temp.matrix[i][j] = sum;
}
}
return temp;
}
我不確定這是否有助於澄清,但這是我的界面Arithmetics:
public interface Arithmetics<T> {
public T zero();
public T add( T a, T b );
public T subtract( T a, T b);
public T multiply (T a, T b);
public T parseString( String str );
public String toString( T a );
}
這是我的一個類DoubleArithmetics,只是為了展示我是如何實現這個界面的:
public class DoubleArithmetics implements Arithmetics<Double> {
protected Double value;
public Double zero()
{
return new Double(0);
}
public Double add( Double a, Double b )
{
return new Double(a.doubleValue()+b.doubleValue());
}
public Double subtract (Double a, Double b)
{
return new Double(a.doubleValue()-b.doubleValue());
}
public Double multiply (Double a, Double b)
{
return new Double(a.doubleValue()*b.doubleValue());
}
public Double parseString( String str )
{
return Double.parseDouble(str);
}
public String toString( Double a )
{
return a.toString();
}
}
只需使用您在界面上已有的zero
方法來初始化sum
:
T sum = arithmetics.zero();
對於非零初始化,您還可以添加采用long
和double
值的方法並為它們返回T
:
public interface Arithmetics<T> {
public T zero();
public T create(long l);
public T create(double d);
public T add( T a, T b );
public T subtract( T a, T b);
public T multiply (T a, T b);
public T parseString( String str );
public String toString( T a );
}
然后實現它們:
public Double create(long l) {
return new Double(l);
}
public Double create(double d) {
return new Double(d);
}
最后,使用它們:
T one = arithmetics.create(1);
由於類型擦除,在Java中實例化泛型有點棘手。
我的方法是將通用類的構造函數傳遞給兩個項:(1)特定於類型T的java.lang.reflect.Constructor; (2)一個Object []數組,其中包含一個特定於類型T的默認值。
當您稍后想要實例化並初始化類型T時,您需要調用Constructor.newInstance(Object [])。 在下面的代碼中,MyGenericClass類代表您的泛型類(看起來像是從原始帖子中稱為Matrix)。
我從InstantiationException獲取了newInstance()和Java中泛型類型的Create實例的解決方案?
public class MyGenericClass<T>
{
Constructor _constructorForT;
Object[] _initialValueForT;
public MyGenericClass(Constructor constructorForT,
Object[] initialValueForT)
{
_constructorForT = constructorForT;
_initialValueForT = initialValueForT;
}
public void doSomething()
{
T sum = initializeT(_constructorForT, _initialValueForT);
System.out.printf("d = %f\n", sum);
}
@SuppressWarnings("unchecked")
private T initializeT(Constructor constructor, Object[] args)
{
T result = null;
try
{
result = (T) constructor.newInstance(args);
}
catch (java.lang.InstantiationException ex)
{
}
catch (java.lang.IllegalAccessException ex)
{
}
catch (java.lang.reflect.InvocationTargetException ex)
{
}
return result;
}
public static void main(String argv[]) throws Exception
{
Constructor constructor =
Double.class.getConstructor(new Class[]{double.class});
Object[] initialValue = new Object[] { new Double(42.0) };
MyGenericClass<Double> myGenericClass =
new MyGenericClass<Double>(constructor, initialValue);
myGenericClass.doSomething();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.