‘壹’ java中如何获取方法名字
import java.lang.reflect.Method;
public class Users {
public void print() {
}
public void getName() {}
public static void main(String[] args) {
Class c = Users.class;
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
System.out.println("方法名" + m[i].getName());
}
}
}
‘贰’ java如何动态获取方法名
public class Test {
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
A a=new A();
String i="setB";
Method cc=a.getClass().getMethod(i, String.class);//获取方法
//String.class如果没有就是new Class[0]
System.out.println(cc.getName());
cc.invoke(a, "aa");
//调用方法
System.out.println(a.getB());
}
}
class A{
private int a=0;
private String b="abc";
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}
‘叁’ JAVA可以在方法里面调出类信息,怎么调出方法的信息,比如获得方法的方法名
你如果可以获得类的星系,可以根据java的反射机制找到方法的信息。
Class clazz就是你获得的类,那么clazz.getMethods()可以获得所有的方法。
具体的查阅相关的 api
‘肆’ 如何在java方法中获得当前方法的名称
在java方法中获得当前方法的名称方法:
一、获得当前类名:
Java代码
this.getClass().getName();
二、获得当前方法名臣:
JDK1.4
Java代码
newException().getStackTrace()[i].getMethodName();//其中i=0就是当前的类的方法名字;i==1就是调用者的方法
JDK1.5之后可用
Java代码
Thread.currentThread().getStackTrace()[1].getMethodName();//具体使用数组的那个元素和JVM的实现有关,我在SUNJDK6下面测试的是第二个元素,具体说明可以查看Thread.getStackTrace方法的javadoc
‘伍’ java怎么获取方法参数名
在java中,可以通过反射获取到类、字段、方法签名等相关的信息,像方法名、返回值类型、参数类型、泛型类型参数等,但是不能够获取方法的参数名。在实际开发场景中,有时需要根据方法的参数名做一些操作,比如像spring-mvc中,@RequestParam、@PathVariable注解,如果不指定相应的value属性,默认就是使用方法的参数名做为HTTP请求的参数名,它是怎么做到的呢?
在这样情况下,有两种方法获取方法来解决这种需求,第一种方法是使用注解,在注解中指定对应应的参数名称,在需要使用参数名称时,获取注解中相应的值即可。第二种方法是从字节码中获取方法的参数名,但是这有一个限制,只有在编译时使用了-g或-g:vars参数生成了调试信息,class文件中才会生成方法参数名信息(在本地变量表LocalVariableTable中),而使用-g:none方式编译的class文件中是没有方法参数名信息的。所以要想完全不依赖class文件的编译模式,就不能使用这种方式。
‘陆’ java怎么获取src目录下所有的包名,类名,方法名 以及通过一个类名获得该类下的所有方法名
可以使用以下代码来获取src目录下所有的包名,类名,方法名 以及通过一个类名获得该类下的所有方法名。
import java.io.File;
import java.lang.reflect.Method;
public class LoopApp {
public static void main(String[] args) throws Exception {
String packageName = "";
File root = new File(System.getProperty("user.dir") + "\\src");
loop(root, packageName);
}
public static void loop(File folder, String packageName) throws Exception {
File[] files = folder.listFiles();
for (int fileIndex = 0; fileIndex < files.length; fileIndex++) {
File file = files[fileIndex];
if (file.isDirectory()) {
loop(file, packageName + file.getName() + ".");
} else {
listMethodNames(file.getName(), packageName);
}
}
}
public static void listMethodNames(String filename, String packageName) {
try {
String name = filename.substring(0, filename.length() - 5);
Object obj = Class.forName(packageName + name);
Method[] methods = obj.getClass().getDeclaredMethods();
System.out.println(filename);
for (int i = 0; i < methods.length; i++) {
System.out.println("\t" + methods[i].getName());
}
} catch (Exception e) {
System.out.println("exception = " + e.getLocalizedMessage());
}
}
}
‘柒’ java 在字符串中截取方法名
importjava.util.HashMap;
importjava.util.Map;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;
publicclassParseString{
privatestaticfinalStringPARAM_KEY="!";
publicstaticvoidmain(String[]args)throwsException{
//待解析字符串
Stringmethod="methodName(methodName2(methodName4(2,3,4),2),methodName3(),strName)";
//这句很重要,先删除字符串中所有的空格,后面的正则中不再需要考虑空字符问题
method=method.replaceAll("\s+","");
//输出结果
for(Map.Entry<String,Integer>entry:parseMethod(method).entrySet()){
System.out.println(entry.getKey()+"---"+entry.getValue());
}
}
privatestaticMap<String,Integer>parseMethod(Stringmethod){
Map<String,Integer>ret=newHashMap<>();
Patternp=Pattern.compile("^([^\(]+)\((.*)\)$");
Matcherm=p.matcher(method);
if(!m.find())
thrownewRuntimeException("错误的方法字符串:"+method);
//找到方法
Map<String,Integer>paramMap=parseParams(m.group(2));
ret.put(m.group(1).trim(),paramMap.remove(PARAM_KEY));
ret.putAll(paramMap);
returnret;
}
privatestaticMap<String,Integer>parseParams(Stringparams){
Map<String,Integer>ret=newHashMap<>();
intcount=0;
while(params.length()>0){
if(params.split(",")[0].indexOf("(")>=0){
//第一个参数为方法
Stringmethod=findFirstMethod(params);
params=(method.length()==params.length())?"":params.substring(method.length()+1);
ret.putAll(parseMethod(method));
}else{
//第一个参数为非方法
params=params.replaceAll("[^,]+(,(.+))*","$2");
}
count++;
}
ret.put(PARAM_KEY,count);
returnret;
}
(Stringparams){
Stringmethod="";
booleanstart=false;
intmatchCount=0;
for(inti=0;i<params.length();i++){
charch=params.charAt(i);
if(ch=='('){
start=true;
matchCount++;
}elseif(ch==')'){
matchCount--;
}
method+=params.substring(i,i+1);
if(start&&matchCount==0)break;
}
if(start)
returnmethod;
thrownewRuntimeException("错误的参数字符串:"+params);
}
}
‘捌’ Java如何获取方法参数中的名称
一、从注解中获取
使用注解方式,我们需要自定义一个注解,在注解中指定参数名,然后通过反射机制,获取方法参数上的注解,从而获取到相应的注解信息。这里自定义的注解是Param,通过value参数指定参数名,定义了一个工具类ParameterNameUtils来获取指定方法的参数名列表,这里获取测试类ParameterNameTest中定义的方法method1的参数名列表表,下面是具体的代码。
‘玖’ Java如何获取方法参数的参数名称
packagecom.mikan;
importjava.lang.annotation.*;
/**
*@authorMikan
*@date2015-08-0423:39
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public@interfaceParam{
Stringvalue();
}
获取注解中的参数名的工具类:
packagecom.mikan;
importjava.lang.annotation.Annotation;
importjava.lang.reflect.Method;
/**
*@authorMikan
*@date2015-08-0500:26
*/
publicclassParameterNameUtils{
/**
*获取指定方法的参数名
*
*@parammethod要获取参数名的方法
*@return按参数顺序排列的参数名列表
*/
publicstaticString[](Methodmethod){
Annotation[][]parameterAnnotations=method.getParameterAnnotations();
if(parameterAnnotations==null||parameterAnnotations.length==0){
returnnull;
}
String[]parameterNames=newString[parameterAnnotations.length];
inti=0;
for(Annotation[]parameterAnnotation:parameterAnnotations){
for(Annotationannotation:parameterAnnotation){
if(annotationinstanceofParam){
Paramparam=(Param)annotation;
parameterNames[i++]=param.value();
}
}
}
returnparameterNames;
}
}
测试类:
packagecom.mikan;
importjava.lang.reflect.Method;
importjava.util.Arrays;
/**
*@authorMikan
*@date2015-08-0423:40
*/
publicclassParameterNameTest{
publicvoidmethod1(@Param("parameter1")Stringparam1,@Param("parameter2")Stringparam2){
System.out.println(param1+param2);
}
publicstaticvoidmain(String[]args)throwsException{
Class<ParameterNameTest>clazz=ParameterNameTest.class;
Methodmethod=clazz.getDeclaredMethod("method1",String.class,String.class);
String[]parameterNames=ParameterNameUtils.(method);
System.out.println(Arrays.toString(parameterNames));
}
}
‘拾’ Java语言如何获取当前正在使用方法的方法名。
System.out.println(new Throwable().getStackTrace()[0]);
执行结果
com..TestMain.main(TestMain.java:71)
包名com.
类名Testmain
方法名main,
处于方法行数71行