这是我的主要课程:-
import io.*;
import processors.*;
import utilities.*;
import java.util.Scanner;
import java.io.IOException;
public class Main
{
public static void main(String[] args)
{
AbstractCalcIO cio = null;
//read properties file to know which type of operation needed.
//then create appropriate class based on that.
try {
String opm = PropertyReader.getProperty("config.properties","opmode");
System.out.println("Got input class name: "+opm);
//get the class object from the name of the input class
Class c = Class.forName(opm);
//then cast it to AbstractCalcIO and then assign it to cio object
Object obj = c.newInstance();
cio = (AbstractCalcIO)obj;
if(cio != null)
{
cio.startOperations();
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
在这个项目中,我使用抽象类、3-IO 类进行输入控制、异常类等。这里我使用反射来避免代码重复。这里还有一个控制功能的属性文件。但是在我使用反射的主类中,我收到了一个通知。出于这个原因,我的项目文件没有被编译。我认为它发生在 java 版本上,我使用 javac 10.0.2。那么,解决方案是什么?
在主类中,反射代码部分是:-
Class c = Class.forName(opm);
//then cast it to AbstractCalcIO and then assign it to cio object
Object obj = c.newInstance();
cio = (AbstractCalcIO)obj;
属性文件是:-
datafile=E:\\java\\calcproject\\cdata.txt
opmode=io.CalcIOSingle
calcmode=sc
所以,最后我收到了这个通知:-
E:\java\calcproject>javac Main.java
Note: Main.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
解决方案将针对此问题:- 对于 Java 版本 10.0.2,将使用默认构造函数。
Class<?> c = Class.forName(opm);
//here need to use default constructor
Constructor<?> cons = c.getDeclaredConstructor();
Object obj = cons.newInstance();
cio = (AbstractCalcIO)obj;
忽然笑
相关分类