郑孟龙 2019-12-05 14:54 采纳率: 0%
浏览 1753

java编写一个函数,接受任意类型参数,返回其参数的长度

今天去面试,上机题,第一题就给我难住了求助各位大佬。。。
图片说明

  • 写回答

2条回答 默认 最新

  • little_how 2019-12-05 19:30
    关注

    简单的实现了一个方法

    import com.google.common.collect.Lists;
    import com.google.common.collect.Sets;
    
    import java.lang.reflect.*;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.ConcurrentHashMap;
    
    public class TestLength {
    
        private static Map<Class, Method> methods = new ConcurrentHashMap<>();
        private static Set<String> methodNames = Sets.newHashSet("length", "size");
    
        public static int length(Object obj) {
            int size = 0;
            if (obj == null) {
                //skip
            } else if (obj instanceof String) {
                size = ((String) obj).length();
            } else if (obj instanceof Collection) {
                size = ((Collection) obj).size();
            } else if (obj instanceof Map) {
                size = ((Map) obj).size();
            } else if (obj.getClass().isArray()) {
                size = ((Object[]) obj).length;
            } else {
                //支持自定义size或者length方法(必须是public、非静态、无参、返回类型为int/Integer的才行)
                size = findLengthOrSize(obj);
            }
            return size;
        }
    
        private static int findLengthOrSize(Object obj) {
            Class clazz = obj.getClass();
    
            //如果没有找到属性,则找length和size的方法
            Method method = getLengthOrSizeMethod(clazz);
            if (method != null) {
                try {
                    return (Integer) method.invoke(obj);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
            return obj.toString().length();
        }
    
        /**
         * 这里可以加一层缓存,同样类型的直接从缓存取,增加性能
         */
        public static Method getLengthOrSizeMethod(Class clazz) {
            Method method = methods.get(clazz);
            if (method == null && !methods.containsKey(clazz)) {
                Method[] methodTmp = clazz.getDeclaredMethods();
                for (Method m : methodTmp) {
                    if (methodNames.contains(m.getName()) && checkMethod(m)) {
                        method = m;
                        break;
                    }
                }
                methods.put(clazz, method);
            }
            return method;
        }
    
        public static boolean checkMethod(Method method) {
            int modifier = method.getModifiers();
            return method.getParameterCount() == 0
                    && Modifier.isPublic(modifier)
                    && !Modifier.isStatic(modifier)
                    && (method.getReturnType() == int.class
                    || method.getReturnType() == Integer.class);
        }
    
        public Integer length() {
            return 55;
        }
    
        public int length(int a, int b) {
            return a + b;
        }
    
        public static void main(String[] args) {
            System.out.println(length("1234"));
            System.out.println(length(Lists.newArrayList("asdf", "asd", "asdf")));
            System.out.println(length(123123));
            Map<String, String> map = new HashMap<>();
            map.put("123","22");
            System.out.println(length(map));
            System.out.println(map.size());
            System.out.println(length(map.keySet()));
            System.out.println(length(new String[]{"123", "1", "2", "3", "34", "123"}));
            System.out.println(length(new TestLength()));
        }
    
    }
    

    希望对你有帮助...

    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧