Trying to create a generic array

L

lbrtchx

I am getting an "incompatible types" compile time error, even though
to me (and apparently to the compiler too) these are just three forms
to refer to the same class:

1) ai.class;
2) Class.forName("ai");
3) ((Class.forName("ai")).newInstance()).getClass();

Here is the actual code example:

// ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
import java.util.*;
import java.lang.reflect.*;

class ai{
String a;
int i;
}

class gnrx10{
gnrx10(){}

public <T> T[] createTypeAr(Class<T> Tp, int iSz){
T[] TpAr = (T[])Array.newInstance(Tp, iSz);
return(TpAr);
}
}

public class gnrx10Test{
public static void main(String args[]){
gnrx10 g = new gnrx10();

// __ this works fine!
String[] aSAr = g.createTypeAr(String.class, 4);
System.out.println("// __ aSAr.length: |" + aSAr.length + "|");

ai[] aiAr = g.createTypeAr(ai.class, 16);
System.out.println("// __ aiAr.length: |" + aiAr.length + "|");
// __
try{

System.out.println(ai.class);
System.out.println(Class.forName("ai"));
System.out.println(((Class.forName("ai")).newInstance()).getClass());

// __ this doesn't!
/*
Class K = ai.class;
System.out.println(K);
aiAr = g.createTypeAr(K, 8);
System.out.println("// __ aiAr.length: |" + aiAr.length + "|");

gnrx10Test.java:47: incompatible types
found : java.lang.Object[]
required: ai[]
aiAr = g.createTypeAr(K, 8);
^
*/

}catch(ClassNotFoundException KNFX){ KNFX.printStackTrace(); }
catch(InstantiationException InstX){ InstX.printStackTrace(); }
catch(IllegalAccessException IlgAxX){ IlgAxX.printStackTrace(); }
}
}
 
L

lbrtchx

OK, all these cases work fine:

Class<KAI> K00 = KAI.class;

Class<KAI> K02 = (Class<KAI>)Class.forName("KAI");

Class<? extends KAI> K04 = (Class<KAI>)Class.forName("KAI");

Class<? extends KAI> K06 = (Class<? extends
KAI>)Class.forName("KAI");

But what I am really trying to do is just do it based on a string
declaring the name of the class, namely "KAI", without using type
declarations "Class<KAI>"-like in the code

1) Say you gain some info about a DTO you will use, then

2) you use reflection to actually make such an object, say "KAI"

3) you save then the class in a reachable place and load a second
class which will be the one using "KAI" objects

How could you do that?

lbrtchx
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top