如何对Class <! - ? - >的对象执行方法

时间:2015-12-04 12:48:04

标签: java class reflection

我想在类的对象上运行时可以从类执行方法吗?

首先:我有一个方法可以给我一个类:

public static Class<?> getClassById(Long id) throws ClassNotFoundException {
    if(d.id == 1L) {
        return First.class;
    } else if(d.id ==2L) {
        return Second.class;
    } else if(d.id ==3L) {
        return Third.class;
    } else {
        throw new ClassNotFoundException();
    }
}

第二:我执行它的方式:

Index.GetClassById(1)应该归还给我。现在我想从该类执行方法myMethod()。顺便说一句,每个类(第一,第二,第三)都有这个myMethod()方法。

请帮忙。

5 个答案:

答案 0 :(得分:4)

Class对象是表示您的类的类型的实例。这意味着First.class.equals(new First())将始终返回false。

你想要的是基于你的类创建一个对象,并在该类上调用你的方法myMethod(),假设你的类(First,Second,Third)有一个默认的构造函数:

Class clazz = Index.getClassById(1);
First first = (First)clazz.newInstance();
first.myMethod();

这种方法的缺点是你必须明确地转换对象。

为了整齐地传递工作,你应该定义一个定义myMethod()

的界面
public interface MyInterface {
  void myMethod();
}
public class First implements MyInterface {
...
}
public class Second implements MyInterface {
...
}
public class Third implements MyInterface {
...
}

然后您可以将上面的方法定义为:

public static Class<MyInterface> getClassById(Long id) throws ClassNotFoundException {
    if(d.id == 1L) {
        return First.class;
    } else if(d.id ==2L) {
        return Second.class;
    } else if(d.id ==3L) {
        return Third.class;
    } else {
        throw new ClassNotFoundException();
    }
}

并称之为:

Class<MyInterface> clazz = Index.getClassById(1);
MyInterface instance = clazz.newInstance();
instance.myMethod();

答案 1 :(得分:1)

由于你有一个类实例,你可以得到它的对象实例,然后按方法名称调用它的方法:

//empty patameters array, to specify the method signature
Class noparams[] = {};
//get the class
Class cls = getClassById(1L);
//get an instance of the class
Object obj = cls.newInstance();
//get some method of the class by it's signatute (name and input parameters)
Method method = cls.getDeclaredMethod("myMethod", noparams);
//invoke this method without parameters
method.invoke(obj, null);

但是具有一些通用接口的解决方案更可取,那么您可以获取此接口的实例并以通常的方式调用它。

答案 2 :(得分:1)

您谈到的问题是一种名为抽象设计模式的设计模式,其中包含所有类。

第1步 为Shapes创建一个界面。

Shape.java

public interface Shape {
   void draw();
}

第2步 创建实现相同接口的具体类。

Rectangle.java

public class Rectangle implements Shape {

   @Override
   public void draw() {
   System.out.println("Inside Rectangle::draw() method.");
  }
 }

Square.java

public class Square implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}

Circle.java

public class Circle implements Shape {

   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}

第3步 为Colors创建一个界面。

Color.java

public interface Color {
   void fill();
}

第四步 创建实现相同接口的具体类。

Red.java

public class Red implements Color {

   @Override
   public void fill() {
      System.out.println("Inside Red::fill() method.");
   }
}

Green.java

public class Green implements Color {

   @Override
   public void fill() {
      System.out.println("Inside Green::fill() method.");
   }
}

Blue.java

public class Blue implements Color {

   @Override
   public void fill() {
      System.out.println("Inside Blue::fill() method.");
   }
}

第5步 创建一个Abstract类来获取Color和Shape Objects的工厂。

AbstractFactory.java

public abstract class AbstractFactory {
   abstract Color getColor(String color);
   abstract Shape getShape(String shape) ;
}  

第6步 创建扩展AbstractFactory的Factory类,根据给定的信息生成具体类的对象。

ShapeFactory.java

    public class ShapeFactory extends AbstractFactory {

       @Override
       public Shape getShape(String shapeType){

  if(shapeType == null){
     return null;
  }     

  if(shapeType.equalsIgnoreCase("CIRCLE")){
     return new Circle();

  }else if(shapeType.equalsIgnoreCase("RECTANGLE")){
     return new Rectangle();

  }else if(shapeType.equalsIgnoreCase("SQUARE")){
     return new Square();
  }

  return null;
   }

   @Override
   Color getColor(String color) {
  return null;
    }
}

ColorFactory.java

public class ColorFactory extends AbstractFactory {

   @Override
   public Shape getShape(String shapeType){
  return null;
  }

   @Override
   Color getColor(String color) {

  if(color == null){
     return null;
  }     

  if(color.equalsIgnoreCase("RED")){
     return new Red();

  }else if(color.equalsIgnoreCase("GREEN")){
     return new Green();

  }else if(color.equalsIgnoreCase("BLUE")){
     return new Blue();
  }

  return null;
   }
   }

第7步 创建Factory生成器/生成器类以通过传递诸如Shape或Color

之类的信息来获取工厂

FactoryProducer.java

public class FactoryProducer {
   public static AbstractFactory getFactory(String choice){

  if(choice.equalsIgnoreCase("SHAPE")){
     return new ShapeFactory();

  }else if(choice.equalsIgnoreCase("COLOR")){
     return new ColorFactory();
  }

  return null;
  }
}

第8步 使用FactoryProducer获取AbstractFactory,以便通过传递类型等信息来获取具体类的工厂。

AbstractFactoryPatternDemo.java

public class AbstractFactoryPatternDemo {
   public static void main(String[] args) {

  //get shape factory
  AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");

  //get an object of Shape Circle
  Shape shape1 = shapeFactory.getShape("CIRCLE");

  //call draw method of Shape Circle
  shape1.draw();

  //get an object of Shape Rectangle
  Shape shape2 = shapeFactory.getShape("RECTANGLE");

  //call draw method of Shape Rectangle
  shape2.draw();

  //get an object of Shape Square 
  Shape shape3 = shapeFactory.getShape("SQUARE");

  //call draw method of Shape Square
  shape3.draw();

  //get color factory
  AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");

  //get an object of Color Red
      Color color1 = colorFactory.getColor("RED");

      //call fill method of Red
      color1.fill();

      //get an object of Color Green
      Color color2 = colorFactory.getColor("Green");

      //call fill method of Green
      color2.fill();

      //get an object of Color Blue
      Color color3 = colorFactory.getColor("BLUE");

      //call fill method of Color Blue
      color3.fill();
    }
}

第9步 验证输出。

Circle :: draw()方法。

内部Rectangle :: draw()方法。

Inside Square :: draw()方法。

Red :: fill()方法。

在Green :: fill()方法中。

在Blue :: fill()方法中。

来源: - http://www.tutorialspoint.com/design_pattern/abstract_factory_pattern.htm

答案 3 :(得分:0)

当然可以。拥有<?php if(isset($_POST["submit"])){ // Checking For Blank Fields.. if($_POST["vname"]==""||$_POST["vemail"]==""||$_POST["sub"]==""||$_POST["msg"]==""){ echo "Fill All Fields."; }else{ // Check if the "Sender's Email" input field is filled out $email=$_POST['vemail']; // Sanitize E-mail Address $email =filter_var($email, FILTER_SANITIZE_EMAIL); // Validate E-mail Address $email= filter_var($email, FILTER_VALIDATE_EMAIL); if (!$email){ echo "Don't forget to include your email adress! Otherwise we can't get back to you."; } else{ $subject = $_POST['sub']; $message = $_POST['msg']; $headers = 'From:' . 'Ross@gmail.com' . "\r\n"; // Sender's Email $headers .= 'Cc: chad' . "\r\n"; // Carbon copy to Sender $from = $headers; // Message lines should not exceed 70 characters (PHP rule), so wrap it $message = wordwrap($message, 70); // Send Mail By PHP Mail Function mail("marc.murray.92@gmail.com", $subject, $message, $headers); echo "Thanks for getting in touch! We'll get back to you ASAP."; } } } ?> ,您现在可以实例化它

Class

其中Object t = c.newInstance() 是从您的方法返回的c

现在你可以做到

Class<?>

答案 4 :(得分:0)

使用java反射。这是一个调用String s的'concat'方法的例子:

String s = "Hello, ";
Class myClass = s.getClass();

Method m = myClass.getDeclaredMethod("concat", String.class);
String result = (String)m.invoke(s, "world");

System.out.println(result);