代码之家  ›  专栏  ›  技术社区  ›  Nayantara Jeyaraj

使用Java反射重写另一个类的方法

  •  2
  • Nayantara Jeyaraj  · 技术社区  · 7 年前

    我有一个Java项目,其中有两个类。我需要使用Java反射来首先打印由中的构造函数设置的默认值 ProjectAccount.java mywork.java 类,然后我需要重写 toString() mywork.java

    toString() 具有参数的方法。

    package relive;
    
    public class ProjectAccount {
        private String projectAccountID;
        private double budget;
        public int noOfProjects;
    
        public ProjectAccount(){
            this.projectAccountID = "MARTINDAWS-BillAnalyzer-001";
            this.budget = 120000.00;
            this.noOfProjects = 10;
        }
    
        @Override
        public String toString(){
            return "Project Accoutn ID = " + projectAccountID + " , Project Budget = "+budget + " , No of Projects = "+ noOfProjects;
        }
    }
    

    mywork.java

    package relive;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class mywork {
    
        public static void main(String[] args) {
            try{
                Class<?> clazz = Class.forName("relive.ProjectAccount");
                Constructor<?> constr = clazz.getDeclaredConstructor(null);
                Method mets = clazz.getDeclaredMethod("toString", null);
                Object obj = constr.newInstance(new Object[] {});
    
                //Print Default values
                System.out.println(mets.invoke(obj, null));
    
                String mod_projectAccountID="ORPT-BT-EMP-DEV";
                double mod_budget = 2200000.0;
                int mod_noOfProjects = 20;
    
                //Print new passed values using the overridden method
                System.out.println(mets.invoke(obj, mod_projectAccountID,mod_budget, mod_noOfProjects));        
            }
    
            catch(ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e){
                e.printStackTrace();
            }
        }
        public static String toString(String mod_projectAccountID, double mod_budget, int mod_noOfProjects){
            return "Project Accoutn ID = " + mod_projectAccountID + " , Project Budget = "+mod_budget + " , No of Projects = "+ mod_noOfProjects; 
        }
    
    }
    

    output

    方法尚未确定。如有任何建议,我将不胜感激。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Nayantara Jeyaraj    7 年前

    我刚刚修改了 mywork.java ProjectAccount.java 直接初始化变量并进行设置。

    toString() toString() 方法

    package relive;
    
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    public class answer_a {
    
        public static void main(String[] args) {
            try{
                Class<?> clazz = Class.forName("relive.ProjectAccount");
                Constructor<?> constr = clazz.getDeclaredConstructor(null);
                Method mets = clazz.getDeclaredMethod("toString", null);
                Object obj = constr.newInstance(new Object[] {});
    
                //Print Default values
                System.out.println(mets.invoke(obj, null));
    
                String mod_projectAccountID= "ORPT-BT-EMP-DEV";
                double mod_budget = 2200000.0;
                int mod_noOfProjects = 20;
    
                //Method that accesses the Fields and modifies them with the new variables
    
                Field [] fields = clazz.getDeclaredFields();
                for(int y=0; y<fields.length; y++){
                    fields[y].setAccessible(true);
    
                    if(fields[y].getName() == "projectAccountID"){
                        fields[y].set(obj, mod_projectAccountID);
                    }
                    else if(fields[y].getType().getSimpleName() == "double"){
                        fields[y].set(obj, mod_budget);
                    }
                    else if (fields[y].getType().getSimpleName() == "int"){
                        fields[y].set(obj, mod_noOfProjects);
                    }
                }
    
                System.out.println(mets.invoke(obj, null));
    
            }
            catch(ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e){
                e.printStackTrace();
            }
        }
    
    }
    

    output

        2
  •  -3
  •   André    7 年前

    这里有几个问题。

    1. 重写toString是通过定义实例方法(您的方法是静态的)
    2. mets ,它引用了 ProjectAccount
    3. mywork 不是的子类
    4. 不能添加参数,

    Oracle Docs

    package de.me.example;
    
    public class SuperType {
    
        @Override
        public String toString() {
    
            return "SuperType";
        }
    
    }
    
    
    package de.me.example;
    
    public class SubType extends SuperType {
    
        // this annatotion is syntactic sugar nothing more,
        //it behaves the same without it
        @Override
        public String toString() {
            return "SubType";
        }
    
    }