实例化使用反射实现特定接口的Java类 [英] Instantiate Java classes which implements specific Interface using reflection

查看:1373
本文介绍了实例化使用反射实现特定接口的Java类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是反思的新人。我已经看过一些问题和教程。



让我们假设我有一个界面,它由3个类A,B,C p>

  public interface MyInterface {
doJob();



}



调用每个类

 类<?> processor = Class.forName(com.foo.A); 
Object myclass = processor.newInstance();

不能创建一个对象,我不能将整个过程限制为特定类型。
我只想调用 MyInterface 类型类。



如果我通过com.foo.A它应该创建一个类对象,com.foo.B应该做B类Object,但如果我通过一些com.foo。



如何实现这个?

解决方案

尝试

  MyInterface newInstance(String className)throws ClassNotFoundException,InstantiationException,IllegalAccessException { 
Class<?> cls = Class.forName(className);
if(!MyInterface.class.isAssignableFrom(cls)){
throw new IllegalArgumentException();
}
return(MyInterface)cls.newInstance();
}


I am new to Reflection. I have seen some of the questions and tutorials.

Let's assume I have one interface which's implemented by 3 classes A,B,C

public interface MyInterface {
doJob();

}

Now using reflection I want to invoke each class

Class<?> processor = Class.forName("com.foo.A");
Object myclass = processor.newInstance();

Rather than creating an Object, can't I restrict the whole process to specific type. I want to invoke only MyInterface type classes.

If I pass com.foo.A it should create A class object, com.foo.B should do B class Object, but if I pass some com.foo.D who exists but still doesn't implement MyInterface shouldn't be invoked.

How can I achieve this?

解决方案

try

MyInterface newInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    Class<?> cls = Class.forName(className);
    if (!MyInterface.class.isAssignableFrom(cls)) {
        throw new IllegalArgumentException();
    }
    return (MyInterface) cls.newInstance();
}

这篇关于实例化使用反射实现特定接口的Java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆