简体   繁体   English

如何在数据库中保存类方法?

[英]How to save class method in database?

Is it possible to read all the methods of a java class and save their names in the database?是否可以读取 java 类的所有方法并将它们的名称保存在数据库中?

@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:使用 Java 反射:

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.您可以使用java.lang.Class.getDeclaredMethods()方法,该方法返回Method对象数组,包括公共、受保护、默认(包)访问和私有方法,但不包括继承的方法。

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()公共 java.lang.String methodA()
public java.lang.String methodB() public java.lang.String methodB()

if you want to store only the name of your methods, you can use the getName() method.如果只想存储方法的名称,可以使用getName()方法。 so if you do this:所以如果你这样做:

for(int i = 0; i < methods.length; i++) {
    System.out.println(methods[i].toString());
}

you get this output:你得到这个输出:

methodA方法A
methodB方法B

You can use javassist as well to get all methods at runtime.您也可以使用 javassist 在运行时获取所有方法。 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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM