JavaScript method to get all the parameter names of function


I wrote an JavaScript function to resolve the parameter names of the functions,

function getArgs(func) {
 //  Let's start with regular matching , Gets a string that matches the parameter pattern .
 //  The first 1 The groups are this : ([^)]*)  Any character that is not a close parenthesis
 var args = func.toString().match(/function\s.*?\(([^)]*)\)/)[1];
 //  Separate parameters with commas (arguments string).
 return args.split(",").map(function(arg) {
  //  Remove the comment (inline comments) And the blank space
  return arg.replace(/\/\*.*\*\//, "").trim();
 }).filter(function(arg) {
  //  Make sure there are no  undefined.
  return arg;
 });
}

The above is the detected function. The sample code is as follows:

function myCustomFn(arg1, arg2,arg3) {
 // ...
}
// ["arg1", "arg2", "arg3"]
console.log(getArgs(myCustomFn));

Is a regular expression (regular expression) a good thing? I don’t know about anything else, but in the right context it’s very awesome!

Java: Java gets the name of the current function in a function

public class Test {
  private String getMethodName() {
    StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
    StackTraceElement e = stacktrace[2];
    String methodName = e.getMethodName();
    return methodName;
  }
  public void getXXX() {
    String methodName = getMethodName();
    System.out.println(methodName);
  }
  public void getYYY() {
    String methodName = getMethodName();
    System.out.println(methodName);
  }
  public static void main(String[] args) {
    Test test = new Test();
    test.getXXX();
    test.getYYY();
  }
}

[Operation Result]

getXXX getYYY

【 note 】

Line 5, stacktrace[0].getMethodName() is getStackTrace, stacktrace[1].getMethodName() is getMethodName, stacktrace[2].getMethodName() is the function name of the function calling getMethodName.

// Note: the position inside stacktrace; // [1] is “getMethodName”, [2] is the method calling this method

public static String getMethodName() {
  StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
  StackTraceElement e = stacktrace[2];
  String methodName = e.getMethodName();
  return methodName;
}

The above content is to introduce js function all parameter names method, this article is not good also please forgive me, welcome to put forward valuable advice.