Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

can i change a non-static method to static method? #439

Open
zhangzishen9 opened this issue Nov 22, 2022 · 1 comment
Open

can i change a non-static method to static method? #439

zhangzishen9 opened this issue Nov 22, 2022 · 1 comment

Comments

@zhangzishen9
Copy link

zhangzishen9 commented Nov 22, 2022

i want to create a new class by template class and change template class'non-static method to static method

import javassist.ClassPool;
import javassist.CtClass;
import javassist.Modifier;

public class Template {
    public void templateMethod(Object arg) {
        //do something
    }

    public static void main(String[] args) throws Exception {
        ClassPool pool = ClassPool.getDefault();
        CtClass template = pool.get("Template");
        CtClass newClass = pool.makeClass(template.getClassFile());
        newClass.setName("FinalClass");
        newClass.getDeclaredMethod("templateMethod", new CtClass[]{pool.get(Object.class.getName())}).setModifiers(Modifier.PUBLIC | Modifier.STATIC);

        Class result = newClass.toClass(sun.misc.Launcher.getLauncher().getClassLoader());
    }
}

    

but finall will throw error:

Type top (current frame, locals[0]) is not assignable to reference type
@FedericoBruzzone
Copy link

Before the fix maybe you can use:


class MyClassLoader extends ClassLoader { ... }

public class Template {
    . . .
    byte[] b = newClass.toBytecode()
    ClassLoader cl = new MyClassLoader.defineClass(newClass.getName(), b, 0, b.length)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants