¿Cómo paso una clase como parámetro en Java?


¿Hay alguna manera de pasar la clase como un parámetro en Java y disparar algunos métodos de esa clase?

void main()
{
    callClass(that.class)
}

void callClass(???? classObject)
{
    classObject.somefunction
    // or 
    new classObject()
    //something like that ?
}

Estoy usando Google Web Toolkit y no admite reflexión.

Author: Michael Dorner, 2011-02-02

9 answers

public void foo(Class c){
        try {
            Object ob = c.newInstance();
        } catch (InstantiationException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Cómo invocar método usando reflexión

 import java.lang.reflect.*;


   public class method2 {
      public int add(int a, int b)
      {
         return a + b;
      }

      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("method2");
           Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Method meth = cls.getMethod(
              "add", partypes);
            method2 methobj = new method2();
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj 
              = meth.invoke(methobj, arglist);
            Integer retval = (Integer)retobj;
            System.out.println(retval.intValue());
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

Véase también

 95
Author: Jigar Joshi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-03 04:37:58
public void callingMethod(Class neededClass) {
    //Put your codes here
}

Para llamar al método, lo llamas de esta manera:

callingMethod(ClassBeingCalled.class);
 33
Author: Olanrewaju O. Joseph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-29 15:45:23

Use

void callClass(Class classObject)
{
   //do something with class
}

Un Class también es un objeto Java, por lo que puede referirse a él utilizando su tipo.

Lea más al respecto en documentación oficial.

 4
Author: darioo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-02 10:04:46

Este tipo de cosas no es fácil. Aquí hay un método que llama a un método estático:

public static Object callStaticMethod(
    // class that contains the static method
    final Class<?> clazz,
    // method name
    final String methodName,
    // optional method parameters
    final Object... parameters) throws Exception{
    for(final Method method : clazz.getMethods()){
        if(method.getName().equals(methodName)){
            final Class<?>[] paramTypes = method.getParameterTypes();
            if(parameters.length != paramTypes.length){
                continue;
            }
            boolean compatible = true;
            for(int i = 0; i < paramTypes.length; i++){
                final Class<?> paramType = paramTypes[i];
                final Object param = parameters[i];
                if(param != null && !paramType.isInstance(param)){
                    compatible = false;
                    break;
                }

            }
            if(compatible){
                return method.invoke(/* static invocation */null,
                    parameters);
            }
        }
    }
    throw new NoSuchMethodException(methodName);
}

Actualización: Espera, acabo de ver la etiqueta de Gwt en la pregunta. No se puede usar reflexión en GWT

 1
Author: Sean Patrick Floyd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-02 10:15:19

No estoy seguro de lo que está tratando de lograr, pero es posible que desee considerar que aprobar una clase puede no ser lo que realmente necesita hacer. En muchos casos, tratar con Clase como esta se encapsula fácilmente dentro de un patrón de fábrica de algún tipo y el uso de eso se hace a través de una interfaz. aquí está uno de docenas de artículos sobre ese patrón: http://today.java.net/pub/a/today/2005/03/09/factory.html

El uso de una clase dentro de una fábrica se puede variedad de formas, más notablemente al tener un archivo de configuración que contiene el nombre de la clase que implementa la interfaz requerida. Entonces la fábrica puede encontrar esa clase desde dentro de la ruta de clase y construirla como un objeto de la interfaz especificada.

 1
Author: Jorel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-02 17:22:37

Como usted ha dicho GWT no soporta la reflexión. Debe usar enlace diferido en lugar de reflexión, o biblioteca de terceros como gwt-ent para support reflexión en la capa gwt.

 0
Author: Gursel Koca,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-02 12:50:16

Clase como paramater. Ejemplo.

Tres clases:

class TestCar {

    private int UnlockCode = 111;
    protected boolean hasAirCondition = true;
    String brand = "Ford";
    public String licensePlate = "Arizona 111";
}

--

class Terminal {

public void hackCar(TestCar car) {
     System.out.println(car.hasAirCondition);
     System.out.println(car.licensePlate);
     System.out.println(car.brand);
     }
}

--

class Story {

    public static void main(String args[]) {
        TestCar testCar = new TestCar();
        Terminal terminal = new Terminal();
        terminal.hackCar(testCar);
    }

}

En el método Terminal de clase hackCar() toma la clase TestCar como parámetro.

 0
Author: romangorbenko.com,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-01 15:18:49

Se estos: http://download.oracle.com/javase/tutorial/extra/generics/methods.html

Aquí está la explicación para los métodos de la plantilla.

 -1
Author: Harold SOTA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-02 10:03:20
 -1
Author: Marcus Gründler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-25 20:23:15