Is it possible to read all the methods of a java class and save their names in the database?
@Entity
public class Action {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public Action() {
}
public String methodA() {
return "methodA";
}
public String methodB() {
return "methodB";
}
}
Use Java reflection:
Method[] methods = Action.class.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
saveToDB(methods[i].toString());
}
you can use the java.lang.Class.getDeclaredMethods()
method which returns an array of Method
objects including public, protected, default (package) access, and private methods, but excludes inherited methods.
Action cls = new Action ();
Class c = cls.getClass();
Method[] methods = c.getDeclaredMethods();
for(int i = 0; i < methods.length; i++) {
System.out.println(methods[i].toString());
}
your output will be something like that:
public java.lang.String methodA()
public java.lang.String methodB()
if you want to store only the name of your methods, you can use the getName()
method. so if you do this:
for(int i = 0; i < methods.length; i++) {
System.out.println(methods[i].toString());
}
you get this output:
methodA
methodB
You can use javassist as well to get all methods at runtime. Even if you don't know about class structure.
ClassPool pool = ClassPool.getDefault();
CtClass cc = pool.get("class Name");
CtMethod[] methods=cc.getDeclaredMethods();
for(CtMethod method:methods){
System.out.println(method.toString());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.