方法不适用于反射

时间:2016-05-25 04:08:21

标签: java dictionary methods reflection

我的一个方法不起作用,我使用map和java反射。我不确定是因为反思或任何其他原因,但它在其他课堂上工作,我没有使用反射。

方法findAccessors()应从map2检索值。该方法在类ReadEdges中定义。此方法由另一个方法findmethod()调用,该方法在类FindMethod中定义。

每当我通过方法findAccessors()调用方法findmethod()时,它返回一个空的链接列表,而不是从map2返回值。课程如下:

班级ReadEdges

import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;

public class ReadEdges {
    static DFSclass dfs = new DFSclass();
    List<String> sourcenodes=new ArrayList<String>();  // source node
    List<String> destinationnodes=new ArrayList<String>(); // destination node
    LinkedHashSet<String> findtransitions=new LinkedHashSet<String>();
    LoanApprovalSystem LS = new LoanApprovalSystem();
    TestdataGeneration testdata = new TestdataGeneration();

    private static final String edgePat = "([a-zA-Z]|[0-9])+(,|\\x20)([a-zA-Z]|[0-9])+";
    private static final String start=dfs.getstart();
    private static final String edge = dfs.getedge();
    private static final String transitions=dfs.gettransitions();
    public static String a;
    public static String b;
    public static String c;
    public static String d;
    private Map<String, LinkedHashSet<String>> map = new HashMap();
    private Map<String, LinkedHashSet<String>> map2 = new HashMap();

     public int getLineCount(String edge){
         int count = edge.split("[\n|\r]").length;
         //System.out.println(count);
            return count;
        }


     public void addEdge(String node1, String node2) throws IOException{

         LinkedHashSet<String> adjacent = map.get(node1);
         {
            if(adjacent==null) {
                adjacent = new LinkedHashSet();
                map.put(node1, adjacent);
            }
            adjacent.add(node2);            
         }

        }

     public void addedgeandAccessor(String edge, String accessor) throws IOException{
         LinkedHashSet<String> adjacent2 = map2.get(edge);
         {
            if(adjacent2==null) {
                adjacent2 = new LinkedHashSet();
                map2.put(edge, adjacent2);
               //System.out.println(map2);
            }

            adjacent2.add(accessor);
            //System.out.println(map2);
         }
     }

    public void ReadEdge(String edgeinput,String transitionsinput,String accessorinput) throws InvalidInputException
    {
        char[] buf = edgeinput.toCharArray();
        BufferedReader br = new BufferedReader(new CharArrayReader(buf));

        char[] buf2 = transitionsinput.toCharArray();
        BufferedReader br2 = new BufferedReader(new CharArrayReader(buf2));     
        String str2 = null;

        char[] buf3 = accessorinput.toCharArray();
        BufferedReader br3 = new BufferedReader(new CharArrayReader(buf3));     
        String str3 = null;

        try 
        {
            //a string for a next edge
            String str = null;
            //a StringTokinizer
            StringTokenizer newNodes = null;
            //get edges and set edges for the graph
            while((((str = br.readLine()) != null) && (str2 = br2.readLine()) != null) && ((str3 = br3.readLine()) != null))
            {
                c=str;
                d=str2;


                LinkedHashSet<String> adjacent = map.get(str);
                if(adjacent==null) {
                    adjacent = new LinkedHashSet();
                    map.put(str, adjacent);
                }
                adjacent.add(str2);

                addedgeandAccessor(str,str3);

                //if the edge inputs are not in good format, throw the exception
                if(!Pattern.matches(edgePat, str.trim()))
                    JOptionPane.showMessageDialog(null,"An invalid input '" + str + "' for an edge. Please read the notes above the forms. ");
                //use a comma to separate tokens
                newNodes = new StringTokenizer (str, ", ");
                //get the value of source node of an edge
                String src = newNodes.nextToken();
                //create the source node and destination node 
                String srcNode = src;
                String desNode = newNodes.nextToken();

                a=srcNode;
                b=desNode;


                addEdge(srcNode, desNode);  
                //System.out.println(adjacent);             
                //findTransition(a,b);
                //findAccessors(a,b);

            }

            //System.out.println(listoftransitions);
        }
            catch (IOException e) {
                JOptionPane.showMessageDialog(null, "Something is Wrong!");
                e.printStackTrace();
            }
}


    public LinkedList<String> adjacentNodes(String last) {
        LinkedHashSet<String> adjacent = map.get(last);
        if(adjacent==null) {
            return new LinkedList();
        }
        return new LinkedList<String>(adjacent);

    }

    public LinkedList<String> findTransition(String node1, String node2) throws IOException{

            LinkedHashSet<String> adjacent = map.get(node1+" "+node2);
            if(adjacent==null) {
                return new LinkedList();
            }
            findtransitions = adjacent;
        return new LinkedList<String>(findtransitions);

    }

    public LinkedList<String> findAccessors(String node1, String node2) {
        LinkedHashSet<String> adjacent = map2.get(node1+" "+node2);
        if(adjacent==null) {
            return new LinkedList();
        }
        System.out.println(adjacent);
        return new LinkedList<String>(adjacent);

    }

public String getsrcNode(){
    return a;
}

public String getedgeline(){
    return c;
}

public String gettransitionline(){
    return d;
}

}

班级FindMethod

import java.util.ArrayList;
import java.util.LinkedList;
import java.lang.reflect.*;

public class FindMethod {

    ReadEdges r = new ReadEdges();
    LoanApprovalSystem LS = new LoanApprovalSystem();
    TestdataGeneration testdata = new TestdataGeneration();


    int method1;
    String method2;
    boolean method3;
    boolean method4;
    String method5;
    String m;


    //returns the method name using refletion
    public String getmethod(Method method){

        FindMethod fm = new FindMethod();
          m = method.getName();         
          String str = "";           

                 str += m+"(" +fm.getparameter(method)+ ")";
               // System.out.println(str);

          return str;
    }


    //returns the parameter name of the method using refletion (i.e. (int))
    public String getparameter(Method method){

        String str = "";
        Class<?>[] params = method.getParameterTypes();
         for (int i = 0; i < params.length; i++) {
             if (i > 0) {
                 str += ", ";
             }
             str += (params[i].getSimpleName());
         }
         return str;
    }

public void findmethod(String s,String t,String transition) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException{

        FindMethod fm = new FindMethod();


        LoanApprovalSystem cls = new LoanApprovalSystem();
        Class<? extends LoanApprovalSystem> c = cls.getClass();
        Object obj = c.newInstance();
        Method[] methods = LoanApprovalSystem.class.getMethods();


          for(Method method : methods)
          {
              //returns the method name (i.e. Receive or Asses)
              m = method.getName();
              fm.getmethod(method);


        if(transition.equals(fm.getmethod(method)) && (transition.equals("Receive(int)")) )
        {
            if(fm.getparameter(method).equals("int") )
            {
                //LS.Receive(testdata.TestData(s,t));
                //invoking the method at runtime where m="Receive".

                method = c.getMethod(m, int.class);
                method.invoke(obj,testdata.TestData(s,t));

                LinkedList<String> accessors= r.findAccessors(s,t);
                System.out.println("A:"+accessors);

                method1=LS.getamount();

                System.out.println(m+"("+method1+")");
                System.out.println("Amount: "+method1);
            }
        } 

}
    }

     public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException
     {
         FindMethod fm = new FindMethod();
         fm.findmethod("1","2","Receive(int)");
     } 
}

有人可以告诉我为什么我的方法findAccessors()findmethod()方法中不起作用吗?或者请给我一个解决这个问题的方法。

注意:此程序中使用了另一个类LoanApprovalSystem ()。如果有人需要,我也可以给出该类的定义。

1 个答案:

答案 0 :(得分:0)

看起来你正在调用ReadEdges的默认构造函数:

'ReadEdges r = new ReadEdges();'

当您需要调用填充地图的构造函数时:

'ReadEdges r = new ReadEdges(edgeinput,transitionsinput,accessorinput);'

编辑: 功能 public void ReadEdge(String edgeinput, String transitionsinput, String accessorinput);永远不会被召唤。

您需要删除void并将其作为's'添加到ReadEdge以使其成为构造函数: public ReadEdges(String edgeinput, String transitionsinput, String accessorinput);

然后,当您在FindMethod类中实例化ReadEdges时,您需要提供参数。

ReadEdges r = new ReadEdges(); 应该: ReadEdges r = new ReadEdges(edgeinput, transitionsinput, accessorinput);

有关更多信息,请阅读“构造函数重载”和“方法重载”。 http://beginnersbook.com/2013/05/constructor-overloading/