Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从类类型转换为接口_Java - Fatal编程技术网

Java 如何从类类型转换为接口

Java 如何从类类型转换为接口,java,Java,我有一个由几个类实现的接口。基于类的全名,我想初始化类对象 接口 public interface InterfaceSample{ } 类文件 public class ABC implements InterfaceSample{ } public class XYZ implements InterfaceSample{ } 一个样本测试类 public class SampleManager{ public static InterfaceSample getInstance(Str

我有一个由几个类实现的接口。基于类的全名,我想初始化类对象

接口

public interface InterfaceSample{
}
类文件

public class ABC implements InterfaceSample{
}
public class XYZ implements InterfaceSample{
}
一个样本测试类

public class SampleManager{
public static InterfaceSample getInstance(String className) {
    InterfaceSample instance = null;
    try {
        instance =  (InterfaceSample) Class.forName(className);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return instance;
}

} 
我得到以下错误,

如何根据其名称初始化类。

您就快到了:

instance =  (InterfaceSample) Class.forName(className).newInstance();
请记住使用以下标记方法:

throws Exception
因为newInstance也被标记为这样,所以准确地说,它会抛出InstantiationException和IllegaccessException。

必须在类上调用newInstance才能获得实例

public class SampleManager{
    public static InterfaceSample getInstance(String className) throws Exception {
        InterfaceSample instance = null;
        try {
            instance =  (InterfaceSample) Class.forName(className).newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return instance;
    }
} 

你对课堂有什么期待。因为名字。。。要回来吗?你真的需要演员吗?不是吗?@sisyphus,职业类型。那是我愚蠢的错误。感谢您的指导。请接受以下描述的答案:
public class SampleManager{
    public static InterfaceSample getInstance(String className) throws Exception {
        InterfaceSample instance = null;
        try {
            instance =  (InterfaceSample) Class.forName(className).newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return instance;
    }
}