Discuss / Java / 真心需要字典类型

真心需要字典类型

Topic source

alienation

#1 Created at ... [Delete] [Delete and Lock User]
public class Main {

   public static void main(String[] args) throws Exception {
      String name = "Xiao Ming";
      int age = 20;
      Person p = new Person();
      Class cls = p.getClass();
      Object[] arg = new Object[] {age,name};
      Field[] fs = cls.getDeclaredFields();
      Method[] ms = cls.getDeclaredMethods();
      for (Field f: fs) {
         var f_type= f.getType().getName();
         for (Object a: arg) {
            var n = a.getClass().getName();
            if (n == "java.lang.Integer") {
               n = "int";
            }
            if (f_type.equals(n)) {
               for (Method m: ms) {
                  try{
                     var para =  m.getParameterTypes()[0].getName();
                     if (para.equals(n)) {
                        m.invoke(p, a);
                     }
                  } catch (ArrayIndexOutOfBoundsException e) {
                     System.out.println(e);
                  }
               }
            }
         }
      }

alienation

#2 Created at ... [Delete] [Delete and Lock User]

迭代字段是多余的

但是为啥age是integer包装类型,不是应该是int基本类型么,换类型把扩展性搞没了

public static void main(String[] args) throws Exception {
   String name = "Xiao Ming";
   int age = 20;
   Person p = new Person();
   Class cls = p.getClass();
   Object[] arg = new Object[] {age,name};
   Method[] ms = cls.getDeclaredMethods();

   for (Object a: arg) {
      var n = a.getClass().getName();
      if (n == "java.lang.Integer") {
         n = "int";
      }
      //找到对应参数类型的方法,填入参数      
      for (Method m: ms) {
         try{
            var para =  m.getParameterTypes()[0].getName();
            if (para.equals(n)) {
               m.invoke(p, a);
            }
         } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(e);
         }
      }
   }

自动装箱懂不,兄弟。你用的是一个Object数组将int类型的age和String类型的name装进去,而int类型的age会自动装箱为Integer类型`

Joker.fu_95

#4 Created at ... [Delete] [Delete and Lock User]

别拿你认为的语言某方面用起来方便就说其他语言的不方便,存在就有它的合理性


  • 1

Reply