![]() ![]() String names = parameterNameDiscoverer.getParameterNames(m) Spring offers a built-in class to accesss parameter ParameterNameDiscoverer parameterNameDiscoverer Inspired by via Java-Reflection Methoden-parameter-Bezeichnung ermitteln (in German) Spring LocalVariable localVariable = localVariableTable.getLocalVariable(0) LocalVariableTable localVariableTable = bcelMethod.getLocalVariableTable() Repository.lookupClass(method.getDeclaringClass()).getMethod(method) Their names can be read using a byte code library such as ASM or BCEL:Ĭom. bcelMethod = The parameters of a method are the first few variables of the variable table. If you compile a Java class with the default settings additional debug info is added to the class files. ![]() I always thought debuggers somehow access the source code to get additional information, but there's another way. However, it's not possible using the official reflection API. That shouldn't come as a surprise: every debugger shows the real parameter names. When I researched the article, I learned parameter names can be read for a long time. If you omit the compiler switch, you can still call parameter.getName(), but the calls yields synthetic names such as arg0, arg1, and arg2. Hence you have to add a compiler switch to enable named parameters: That's for a good reason: the extra information requires more memory, and it might confuse older tools dealing with the byte code. However, parameter names aren't compiled into the byte code by default. Parameter parameters = m.getParameters() Reading the parameter names is as simple as can be: Read the parameter name, and you're done. In theory, you could choose another but why should you? Java 8 makes the annotation superfluous. The annotation simply repeats the parameter name. They introduced the annotation basically because they couldn't access the parameter class EditPetForm = RequestMethod.GET) ![]() But it's attractive for framework programmers, so application programmers will benefit from the feature on the long run. That's just not your frame of mind when you implement business logic. Granted, the average programmer will hardly ever want to read the name of a parameter via reflection. Have you ever seen those annoying synthetic parameter names arg0, arg1, arg2 in the debugger? That's what happens if parameter names get lost. You can read the names of the parameters of a method. Java 8 introduces another feature to the reflection API. But it turned out to be an interesting read nonetheless. At least not the kind of named parameters we know from languages such as Visual Basic, Groovy and many others. I was very surprised when I read Adam Bien's blog post on named parameters in Java 8. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |