Outils pour utilisateurs

Outils du site


instancier_une_classe_par_son_nom

Instancier une classe par son nom

Cet exemple permet d'instancier une classe avec son nom. Une fois l'instance créée, il fait appelle à la méthode affichage toujours par réflexion sur l'instance en cours.

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
 
Object objet;
String s;
int index;
 
void setup() {
  size(800, 600);
  frameRate(1);
  s = "";
  objet = null;
  index = 0;
}
 
void draw() {
  if (objet != null) { // Si objet a déjà été instancié
    Class[] params = new Class[1];
    params[0] = String.class;
    try {
      Method methode = objet.getClass().getMethod("affichage", params);
      // Execute la méthode avec l'instance de la classe passée en paramètre
      methode.invoke(objet, "Bonjour");
    }
    catch(NoSuchMethodException e) {
      e.printStackTrace();
    }
    catch (InvocationTargetException e) {
      e.printStackTrace();
    } 
    catch (IllegalAccessException e) {
      e.printStackTrace();
    }
  }
}
 
void keyPressed() {
  if (s.equals("Objet1")) {
    s = "Objet2";
  } else {
    s = "Objet1";
  }
  Class classe = null;
  try {
    // Sélectionne la classe en fonction du nom
    classe = Class.forName(this.getClass().getName() +"$" + s);
    // Sort la liste des constructeurs de la classe
    Constructor[] constructeurs = classe.getConstructors();
    // Prend le premier constructeur et l'appelle avec les paramètres
    objet = constructeurs[0].newInstance(this, index); // newInstance(new Object[] {this, index})
  } 
  catch (ClassNotFoundException e) {
    e.printStackTrace();
  }
  catch (InstantiationException e) {  
    println("InstantiationException");
    e.printStackTrace();
  }
  catch (IllegalAccessException e) {
    println("IllegalAccessException");
    e.printStackTrace();
  }
  catch (InvocationTargetException e) {
    e.printStackTrace();
  }
  index++;
}
 
class Objet1 {
  public Objet1(int x) {
    println("Objet 1 : " + x);
  }
 
  void affichage(String s) {
    println("Objet1 : Affichage " + s);
  }
}
 
class Objet2 {
  public Objet2(int x) {
    println("Objet 2 : " + x);
  }
 
  void affichage(String s) {
    println("Objet2 : Affichage " + s);
  }
}
instancier_une_classe_par_son_nom.txt · Dernière modification : 2020/04/25 02:04 de Mushussu