为了账号安全,请及时绑定邮箱和手机立即绑定

在java中使用反射的问题

在java中使用反射的问题

慕容3067478 2021-10-17 16:58:52
这是我的主要课程:-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.txtopmode=io.CalcIOSinglecalcmode=sc所以,最后我收到了这个通知:-E:\java\calcproject>javac Main.javaNote: 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;
查看完整描述

1 回答

?
忽然笑

TA贡献1806条经验 获得超5个赞

Class.newInstance方法绕过对默认构造函数的调用,因此可能会抛出异常(不好的做法)。这已经不再被警告了。阅读 javadoc。

所以使用默认(无参数)构造函数:

Object obj = c.getConstructor().newInstance();


查看完整回答
反对 回复 2021-10-17
  • 1 回答
  • 0 关注
  • 175 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信