【问题标题】:Method is not working with reflection方法不适用于反射
【发布时间】:2016-05-25 04:08:20
【问题描述】:

我在 map 和 java 反射中使用的一种方法不起作用。我不确定是因为反射还是任何其他原因,但它在我没有使用反射的其他类中工作。

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

每当我通过方法findmethod() 调用方法findAccessors() 时,它都会返回一个空链接列表,而不是返回来自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 ()。如果有人需要,我也可以给出该类的定义。

【问题讨论】:

    标签: java dictionary methods reflection


    【解决方案1】:

    看起来您正在调用 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/

    【讨论】:

    • 你能说得更具体点吗?怎么做或者我应该在哪里打电话?可以举个例子吗?
    • 我用更多信息更新了我的答案。您需要确保正在调用填充 map2 的“ReadEdge”函数。
    猜你喜欢
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2021-10-03
    • 2011-12-23
    • 2016-10-01
    • 1970-01-01
    相关资源
    最近更新 更多