mardi 1 août 2017

Override a method of another class using Java Reflections

I have a Java Project where I have 2 classes. I need to use Java reflections to first print the default values as set by the constructor in ProjectAccount.java from mywork.java class and then I need to Override the toString() method to pass values from mywork.java class and print them.

I was able to use java reflections to print the default constructor-set values. But I am getting an error when trying to override and print the toString() method with arguments.

ProjectAccount.java

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 and Error

output

I guess that I am encountering this error since I have not overridden the toString() method yet. Any suggestions on how I could override and print this will be highly appreciated.





Aucun commentaire:

Enregistrer un commentaire