Reputation: 31
I am attempting to create a HashMap<Integer, Class>
, and am not being successful. Essentially, all I want to do is have the ability to dynamically load the classes into the Map.
My managed Bean looks like this:
package Demo;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.Dependent;
import javax.inject.Named;
/**
*
* @author kbarnett
*/
@Named(value = "facePalmBean")
@Dependent
public class FacePalmBean {
private HashMap<Integer, Class> chimpanzee;
private NewClass0 NewClass0;
private NewClass1 NewClass1;
private NewClass2 NewClass2;
/**
* Creates a new instance of FacePalmBean
*/
public FacePalmBean() {
chimpanzee = new HashMap<>();
NewClass0 = new NewClass0(0);
NewClass1 = new NewClass1(1);
NewClass2 = new NewClass2(2);
}
public HashMap<Integer, Class> getChimpanzee() {
for (int i = 0; i < 3; i++) {
try {
String tmpstring = "NewClass"+i;
System.out.println(tmpstring);
Class tmpclass = Class.forName(tmpstring);
System.out.println(tmpclass);
chimpanzee.put(i, tmpclass);
} catch (ClassNotFoundException ex) {
Logger.getLogger(FacePalmBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println(chimpanzee.toString());
return chimpanzee;
}
public void setChimpanzee(HashMap<Integer,Class> chimpanzee) {
this.chimpanzee=chimpanzee;
}
}
and the NewClasses look like this:
package Demo;
public class NewClass0 {
Integer MyNumber;
NewClass0(int num){
MyNumber=num;
}
public Integer getMyNumber() {
return MyNumber;
}
}
All of the NewClasses are identical except for the number (i.e. 0, 1, and 2).
Upvotes: 0
Views: 73
Reputation: 35598
In order to load a class with the Class.forName()
method, you must specify a fully qualified package name. In this case it must be Demo.NewClass0
, for example.
Upvotes: 2