Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
In Java6, imagine I have the following method signature: public void makeSandwich(Bread slice1, Bread slice2, List<Filling> fillings, boolean mustard) I would like to know, at runtime, the value that was passed on to slice2 or any other parameter, the important bit here is that I want to get the value by parameter name. I know how to get the list of parameter types with getParameterTy...
In Spring, the two following statements are, if I'm not mistaken, identical: @RequestParam("type") String type @RequestParam String type How can spring know the variable name of 'type' (second version). I was under the impression that this information was removed from the class files unless compiled with the -g flag (include debug information).
  /*
   * Copyright 2002-2008 the original author or authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.springframework.core;
 
 import java.util.Map;
 
 import  org.objectweb.asm.ClassReader;
 import  org.objectweb.asm.Label;
 import  org.objectweb.asm.MethodVisitor;
 import  org.objectweb.asm.Opcodes;
 import  org.objectweb.asm.Type;
 import  org.objectweb.asm.commons.EmptyVisitor;
 
Implementation of ParameterNameDiscoverer that uses the LocalVariableTable information in the method attributes to discover parameter names. Returns null if the class file was compiled without debug information.

Uses ObjectWeb's ASM library for analyzing class files. Each discoverer instance caches the ASM ClassReader for each introspected Class, in a thread-safe manner. It is recommended to reuse discoverer instances as far as possible.

Author(s):
Adrian Colyer
Juergen Hoeller
Since:
2.0
 
 
 	private static Log logger = LogFactory.getLog(LocalVariableTableParameterNameDiscoverer.class);
 
 	private final Map parameterNamesCache = CollectionFactory.createConcurrentMapIfPossible(16);
 
 	private final Map classReaderCache = new HashMap();
 
 
 	public String[] getParameterNames(Method method) {
 		String[] paramNames = (String[]) this..get(method);
 		if (paramNames == null) {
 			try {
 				paramNames = visitMethod(method).getParameterNames();
 				if (paramNames != null) {
 					this..put(methodparamNames);
 				}
 			}
 			catch (IOException ex) {
 				// We couldn't load the class file, which is not fatal as it
 				// simply means this method of discovering parameter names won't work.
 				if (.isDebugEnabled()) {
 					.debug("IOException whilst attempting to read '.class' file for class [" +
 							method.getDeclaringClass().getName() +
 							"] - unable to determine parameter names for method: " + methodex);
 				}
 			}
 		}
 		return paramNames;
 	}
 
 	public String[] getParameterNames(Constructor ctor) {
 		String[] paramNames = (String[]) this..get(ctor);
 		if (paramNames == null) {
 			try {
 				paramNames = visitConstructor(ctor).getParameterNames();
 				if (paramNames != null) {
 					this..put(ctorparamNames);
 				}
 			}
 			catch (IOException ex) {
 				// We couldn't load the class file, which is not fatal as it
 				// simply means this method of discovering parameter names won't work.
 				if (.isDebugEnabled()) {
 					.debug("IOException whilst attempting to read '.class' file for class [" +
 							"] - unable to determine parameter names for constructor: " + ctorex);
				}
			}
		}
		return paramNames;
	}

Visit the given method and discover its parameter names.
		ClassReader classReader = getClassReader(method.getDeclaringClass());
		classReader.accept(classVisitorfalse);
		return classVisitor;
	}

Visit the given constructor and discover its parameter names.
		ClassReader classReader = getClassReader(ctor.getDeclaringClass());
		classReader.accept(classVisitorfalse);
		return classVisitor;
	}

Obtain a (cached) ClassReader for the given class.
	private ClassReader getClassReader(Class clazzthrows IOException {
		synchronized (this.) {
			ClassReader classReader = (ClassReader) this..get(clazz);
			if (classReader == null) {
				InputStream is = clazz.getResourceAsStream(ClassUtils.getClassFileName(clazz));
				if (is == null) {
					throw new FileNotFoundException("Class file for class [" + clazz.getName() + "] not found");
				}
				try {
					classReader = new ClassReader(is);
					this..put(clazzclassReader);
				}
				finally {
					is.close();
				}
			}
			return classReader;
		}
	}


Helper class that looks for a given member name and descriptor, and then attempts to find the parameter names for that member.
	private static abstract class ParameterNameDiscoveringVisitor extends EmptyVisitor {
		private int numParamsExpected;
		/*
		 * The nth entry contains the slot index of the LVT table entry holding the
		 * argument name for the nth parameter.
		 */
		private int[] lvtSlotIndex;
		public ParameterNameDiscoveringVisitor(String nameboolean isStaticClass[] paramTypes) {
			this. = name;
			this. = paramTypes.length;
			computeLvtSlotIndices(isStaticparamTypes);
		}
		public void setDescriptorToMatch(String descriptor) {
			this. = descriptor;			
		}
		public MethodVisitor visitMethod(int accessString nameString descString signatureString[] exceptions) {
			if (name.equals(this.) && desc.equals(this.)) {
				return new LocalVariableTableVisitor(thisisStatic(access));
			else {
				// Not interested in this method...
				return null;
			}
		}
		private boolean isStatic(int access) {
			return ((access & Opcodes.ACC_STATIC) > 0);
		}
		public String[] getParameterNames() {
			return this.;
		}
		private void computeLvtSlotIndices(boolean isStaticClass[] paramTypes) {
			this. = new int[paramTypes.length];
			int nextIndex = (isStatic ? 0 : 1);
			for (int i = 0; i < paramTypes.lengthi++) {
				this.[i] = nextIndex;
				if (isWideType(paramTypes[i])) {
					nextIndex += 2;
				}
				else {
					nextIndex++;
				}
			}
		}
		private boolean isWideType(Class aType) {
			return (aType == . || aType == .);
		}
	}
			super(method.getName(), Modifier.isStatic(method.getModifiers()), method.getParameterTypes());
			setDescriptorToMatch(Type.getMethodDescriptor(method));
		}
	}
			super("<init>"falsector.getParameterTypes());
			Type[] pTypes = new Type[ctor.getParameterTypes().length];
			for (int i = 0; i < pTypes.length; i++) {
				pTypes[i] = Type.getType(ctor.getParameterTypes()[i]);
			}
			setDescriptorToMatch(Type.getMethodDescriptor(Type.VOID_TYPE, pTypes));
		}
	}
	private static class LocalVariableTableVisitor extends EmptyVisitor {
		private final boolean isStatic;
		private boolean hasLvtInfo = false;
		public LocalVariableTableVisitor(ParameterNameDiscoveringVisitor memberVisitorboolean isStatic) {
			this. = memberVisitor;
			this. = isStatic;
			this. = new String[memberVisitor.numParamsExpected];
		}
		public void visitLocalVariable(
				String nameString descriptionString signature, Label start, Label endint index) {
			this. = true;
			int[] lvtSlotIndices = this..;
			for (int i = 0; i < lvtSlotIndices.lengthi++) {
				if (lvtSlotIndices[i] == index) {
					this.[i] = name;
				}
			}
		}
		public void visitEnd() {
			if (this. || (this. && this..length == 0)) {
				 // visitLocalVariable will never be called for static no args methods
				 // which doesn't use any local variables.
				 // This means that hasLvtInfo could be false for that kind of methods
				 // even if the class has local variable info.
			}
		}
	}
New to GrepCode? Check out our FAQ X