import java.util.*; import java.lang.reflect.*; public class PokemonFactory { public static Scanner input = new Scanner(System.in); public static Pokemon newEmptyInstance() throws Exception { System.out.print("Entrer le nom de la classe de Pokemon : "); String className = input.nextLine(); Class c = Class.forName(className); Pokemon np = (Pokemon) c.newInstance(); // ou bien : //Constructor constructeur = c.getConstructor(); //Pokemon np = (Pokemon) constructeur.newInstance(); return np; } public static Pokemon newInstance() throws Exception { Object np = newEmptyInstance(); Field[] fields = np.getClass().getFields(); for(Field f : fields) { System.out.print("Entrer la valeur de l'attribut "+f.getName()+" (un "+f.getType().getName()+") : "); String val = input.nextLine(); if(f.getType().getName().equals("int")){ int a = Integer.parseInt(val); f.set(np,a); } else { if(f.getType().getName().equals("double")){ double x = Double.parseDouble(val); f.set(np,x); } else { assert f.getType().getName().endsWith("String") : "Type incorrect pour l'attribut : "+f.getName(); f.set(np,val); } } } return (Pokemon)np; } public static void main(String[] args) throws Exception { Pokemon p = PokemonFactory.newInstance(); System.out.println(p); } }