利用反射打印对象的所有属性及调用对象方法

Posted 十一路客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用反射打印对象的所有属性及调用对象方法相关的知识,希望对你有一定的参考价值。

利用java反射输出对象的所有属性,调用对象的方法

public class ClassUtil 
   private static final Logger logger = LoggerFactory.getLogger(ClassUtil.class);
   
   public static final boolean isNull(String str)
	   if(str != null && !str.equals(""))
		   return false;
	   
	   return true;
   
   
   /**
	 * 20150729  输出对象的所有属性值
	 * */
	public static String toString(Object obj) 
		String s = ""; 
		try  
		s = getPropertyString(obj); 
		 catch (Exception e)  
		// TODO Auto-generated catch block 
		e.printStackTrace(); 
		 
		return s; 
	 

	public static String getPropertyString(Object entityName) throws Exception  
		Class<? extends Object> c = entityName.getClass(); 
		Field field [] = c.getDeclaredFields(); 
		StringBuffer sb = new StringBuffer(); 

		sb.append("------ " + " begin ------\\n"); 
		for(Field f : field) 
		sb.append(f.getName()); 
		sb.append(" : "); 
		sb.append(invokeMethod(entityName,f.getName(),null)); 
		sb.append("\\n"); 
		 
		sb.append("------ " + " end ------\\n"); 
		return sb.toString(); 
	 

	public static Object invokeMethod(Object owner, String methodName, Object[] args) throws Exception
		Class<? extends Object> ownerClass = owner.getClass();

		methodName = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
		Method method = null;
		try 
		method = ownerClass.getMethod("get" + methodName);
		 catch (SecurityException e) 
		// TODO Auto-generated catch block
		//e.printStackTrace();
		 catch (NoSuchMethodException e) 
		// TODO Auto-generated catch block
		//e.printStackTrace();
		return " can't find 'get" + methodName + "' method";
		

		return method.invoke(owner);
	
	
	//20170217 从oss url地址中获取文件名
		public static String getFileNameFromUrl(String fileUrl)
			String fileName = "";
			if(!ClassUtil.isNull(fileUrl))
				Integer index = fileUrl.lastIndexOf("/");
	    		 if(index>-1)
	    			 fileName = fileUrl.substring(index+1);	 
	    		 
			
			
			return fileName;
		
		
		//20170221 若获取的变量为null 则返回空字符串
		public static String dealStrWithNull(String str)
			return (str == null? "":str);
		
		
		//2017020 将oss url地址中的文件名进行编码后 如http://www.123.com/attachment/201702/20/20170220104327/test1+.jpg
		//对url中的文件名进行utf-8编码  以防文件名中存在加号等特殊符号  导致附件无法下载
		public static String encodeFileNameForUrl(String fileUrl) throws UnsupportedEncodingException
			String fileName = "";
			if(!ClassUtil.isNull(fileUrl))
				Integer index = fileUrl.lastIndexOf("/");
	    		 if(index>-1)
	    			 String urlPrefix = fileUrl.substring(0,index+1);			 
	    			 fileName = fileUrl.substring(index+1);	
	    			 fileName = URLEncoder.encode(fileName,"UTF-8");
	    			 
	    			 fileUrl = urlPrefix + fileName;
	    		 
			
			
			return fileUrl;
		
		
		//对oss url中的文件名进行utf-8解码  以防文件名中存在加号等特殊符号  导致附件无法下载
		public static String decodeFileNameForUrl(String fileUrl) throws UnsupportedEncodingException
			String fileName = "";
			if(!ClassUtil.isNull(fileUrl))
				Integer index = fileUrl.lastIndexOf("/");
		    		if(index>-1)
		    			String urlPrefix = fileUrl.substring(0,index+1);			 
		    			fileName = fileUrl.substring(index+1);	
		    			fileName = URLDecoder.decode(fileName,"UTF-8");
		    			 
		    			fileUrl = urlPrefix + fileName;
		    		
			
				
			return fileUrl;
		
		
		/**
		 * 输出各个类型的字节数
		 * @param args
		 */
		private static void calSize()   
			System.out.println("Integer: " + Integer.SIZE/8);           // 4  
			System.out.println("Short: " + Short.SIZE/8);               // 2      
			System.out.println("Long: " + Long.SIZE/8);                 // 8  
			System.out.println("Byte: " + Byte.SIZE/8);                 // 1  
			System.out.println("Character: " + Character.SIZE/8);       // 2  
			System.out.println("Float: " + Float.SIZE/8);               // 4  
			System.out.println("Double: " + Double.SIZE/8);             // 8  
			System.out.println("Boolean: " + Boolean.toString(false));  
	 
		
		
		/**
		 * 将输入字符串以十进制输出
		 * */
		public static void hexToDecimal1() 
			BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
			String line;
			try 
				while((line = bufr.readLine()) != null) 
					line = line.substring(2);//去掉0x前缀
					int result = Integer.parseInt(line,16);
					System.out.println(result);
				
			catch(IOException e) 
				e.printStackTrace();
			
		
		
		/**
		 * 将输入十六进制字符串以十进制输出
		 * */
		public static void hexToDecimal() 
			BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
			String line;
			BigInteger base = new BigInteger("10");
			try 
				while((line = bufr.readLine()) != null) 
					line = line.substring(2);//去掉0x前缀
					//int result = Integer.parseInt(line,16);
					BigInteger result = new BigInteger("0");
					for(int i=0; i<line.length(); i++) 
						char ch = line.charAt(line.length() - 1 - i);
						if(ch >= 'A' && ch <= 'F') 
							BigInteger tmp = base.pow(i).multiply(new BigInteger(Integer.toString(ch - 'A' + 10)));
							result.add(tmp);
						else 
							BigInteger tmp = base.pow(i).multiply(new BigInteger(Integer.toString(ch)));
							result.add(tmp);
						
					
					
					System.out.println(result);
				
			catch(IOException e) 
				e.printStackTrace();
			
		
		
		/**
		 * 获取利用反射获取类里面的值和名称
		 * @param obj
		 * @return
		 * @throws IllegalAccessException
		 */
		 public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException 
				 Map<String, Object> map = new HashMap<>();
				 Class<?> clazz = obj.getClass();
				 System.out.println(clazz);
				 for (Field field : clazz.getDeclaredFields()) 
					 field.setAccessible(true);
					 String fieldName = field.getName();
					 Object value = field.get(obj);
					 map.put(fieldName, value);
				 
				 return map;
		 
		
		    /**
             * 20181019 添加 调用dao方法  前后 添加日志
             * @param owner 调用的对象或spring bean
             * @param methodName 方法名
             * @param args 参数map
             * @return map
            */
		public static Map<String, Object> invokeDaoMethod(Object owner, String methodName, HashMap<String, Object> args) throws Exception
			Class<? extends Object> ownerClass = owner.getClass();          
			logger.info("class[" + owner.getClass().getName() + "] - method[" + methodName + "]");	
			logger.info("ownerClass: ");
			logger.info("owwnerClass is null? " + (ownerClass == null));
			Method method = null;
			try 
				//method = ownerClass.getMethod(methodName,args.getClass());
				method = ReflectionUtils.findMethod(ownerClass, methodName, args.getClass());
				logger.info("method is null? " + (method == null));
			 catch (SecurityException e) 
				// TODO Auto-generated catch block
				e.printStackTrace();
			 

			return objectToMap(ReflectionUtils.invokeMethod(method, owner, args));
		
		
		public static void main(String[] args) 
			// TODO Auto-generated method stub
			hexToDecimal1();
		

   

 

以上是关于利用反射打印对象的所有属性及调用对象方法的主要内容,如果未能解决你的问题,请参考以下文章

利用java反射调用类的属性和方法

Learning-Python26:反射及内置方法

如何利用java的反射机制动态创建对象

Java基础之反射

JavaSE——反射

java反射的原理及使用