Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8495827
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T23:41:04+00:00 2026-06-10T23:41:04+00:00

I am developing a plugin for a service. For it to function, it needs

  • 0

I am developing a plugin for a service. For it to function, it needs some data that the service does not provide.

A plugin has a strict loading/unloading specification. A bare plugin looks like this:

public class Plugin extends JavaPlugin 
{    
    @Override
    public void onEnable() {} //Plugin enters here. Comparable to main(String[] args)

    @Override
    public void onDisable() {} //Plugin exits here, when service shuts down.
}

There is a package called org.service.aClass. Inside it there is aMethod. aMethod looks like this:

public boolean aMethod(boolean bool) {
return bool;
}

An oversimplified scenario, but it works. My plugin needs to know that value of bool whenever aMethod is called. This is absolutely critical o my program; I have no other way of obtaining that value.

I would advise the aMethod, but since my plugin is loaded after the service this would not work. Load time weaving, from what I understand, won’t be suitable here either, due to being loaded AFTER.

Despite it doesn’t work, here is the aspect I was using, in case it may be of any use:

public aspect LogAspect {

    pointcut publicMethodExecuted(): execution(* org.service.aClass.aMethod(..));

    after(): publicMethodExecuted(){
    cat(String.format("Entered method: %s.",
        thisJoinPoint.getSignature()));

    List<Object> arguments = Arrays.asList(thisJoinPoint.getArgs());
    List<Object> argTypes = new ArrayList<Object>();
    for (Object o: arguments) {  
        argTypes.add(o.getClass().toString());

    }

    cat(String.format("With argument types: %s and values: %s.",
            argTypes, arguments));


    cat(String.format("Exited method: %s.", thisJoinPoint.getSignature()));
    }

 public void cat(Object dog) {
    System.out.println("[TEST] " + dog);
    }

}

I have the AspectJ: In Action book open beside me right now, and on all the load-time weaving examples it mentions that the program must be started with a -javaagent flag. Since my proram is a plugin, there is no way this can happen.

I also looked into ASM. I found a wonderful tutorial on building a profiler (basically what I wish to do) here.

Problem with that is that it once again uses the -javaagent flag when it starts, as well as the public static premain, so it is unsuitable, as I only have onEnable and onDisable.

Then I found out about Java’s Attach API. Which from the looks of it would allow me to attach my agent, the profiler, after a class has been loaded. It seems perfect, but after half an hour searching I could not find a good example of this that I could understand.

Could anyone help? This is a two-in-one question: can AspectJ be used for this? And if so, how? Also, in the case that it cannot, could someone point me in the right direction for using the Attach API with an ASM profiler?

Thanks in advance!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T23:41:05+00:00Added an answer on June 10, 2026 at 11:41 pm

    I did it!

    I created a runtime attacher for the profiler outlined here. Its basically that, with the premain renamed to ‘agentmain’.

    I made a Util class that has the attacher along with other useful functions. The attacher works by creating a jar with the agent, with a manifest stating that it can profile. The Util class looks like this:

        public class Util {
    
        /**
         * Gets the current JVM PID
         * @return
         * Returns the PID
         * @throws Exception
         */
    
        public static String getPidFromRuntimeMBean() {
        String jvm = ManagementFactory.getRuntimeMXBean().getName();
        String pid = jvm.substring(0, jvm.indexOf('@'));
        return pid;
        }
    
        /**
         * Attaches given agent classes to JVM
         * 
         * @param agentClasses
         * A Class<?>[] of classes to be included in agent
         * @param JVMPid
         * The PID of the JVM to attach to
         */
    
        public static void attachAgentToJVM(Class<?>[] agentClasses, String JVMPid) {
    
        try {
    
    
        File jarFile = File.createTempFile("agent", ".jar");
        jarFile.deleteOnExit();
    
        Manifest manifest = new Manifest();
        Attributes mainAttributes = manifest.getMainAttributes();
        mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
        mainAttributes.put(new Attributes.Name("Agent-Class"),
            Agent.class.getName());
        mainAttributes.put(new Attributes.Name("Can-Retransform-Classes"),
            "true");
        mainAttributes.put(new Attributes.Name("Can-Redefine-Classes"), "true");
    
        JarOutputStream jos = new JarOutputStream(new FileOutputStream(
            jarFile), manifest);
    
    
        for(Class<?> clazz: agentClasses) {         
            JarEntry agent = new JarEntry(clazz.getName().replace('.',
                '/')
                + ".class");
            jos.putNextEntry(agent);
    
        jos.write(getBytesFromIS(clazz.getClassLoader()
            .getResourceAsStream(
                clazz.getName().replace('.', '/') + ".class")));
        jos.closeEntry();
        }
    
        jos.close();
        VirtualMachine vm = VirtualMachine.attach(JVMPid);
        vm.loadAgent(jarFile.getAbsolutePath());
        vm.detach();
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        }
    
        /**
         * Gets bytes from InputStream
         * 
         * @param stream
         * The InputStream
         * @return 
         * Returns a byte[] representation of given stream
         */
    
        public static byte[] getBytesFromIS(InputStream stream) {
    
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try {
            int nRead;
            byte[] data = new byte[16384];
    
            while ((nRead = stream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
            }
    
            buffer.flush();
        } catch (Exception e) {
            System.err.println("Failed to convert IS to byte[]!");
            e.printStackTrace();
        }
    
        return buffer.toByteArray();
    
        }
    
        /**
         * Gets bytes from class
         * 
         * @param clazz    
         * The class
         * @return
         * Returns a byte[] representation of given class
         */
    
        public static byte[] getBytesFromClass(Class<?> clazz) {            
        return getBytesFromIS(clazz.getClassLoader().getResourceAsStream( clazz.getName().replace('.', '/') + ".class"));   
        }
    
    }
    

    I included JavaDoc comments for clarity.

    An example of using it would be:

    Util.attachAgentToJVM(new Class<?>[] { Agent.class, Util.class,
            Profile.class, ProfileClassAdapter.class,
            ProfileMethodAdapter.class }, Util.getPidFromRuntimeMBean());   
    

    Remember that the attacher wants Agent.class to be the main agent. You can change this easily. The rest of the Class[] are classes to be included in the temporary agent.jar

    If your IDE complains about “UnsatisfiedLinkError”s, it is because the attach.(dll|so) needed for this only comes with the JDK. Just copy paste it into your %JAVA_PATH%/jre/lib. Also, add a reference to your JDK’s tools.jar, because it contains all the com.sun imports.

    EDIT: I have a working github example is anyone might think this is useful. Its here.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm developing a plugin that has node(computer) objects with attributes like: String name String
I am developing an plugin for OsiriX . In that app i have 3-4
I am developing a plugin that requires retrieval of path/filename of java files. The
I am developing a plugin that requires retrieval of path/filename of java files. The
I am developing an Eclipse plugin and have tests for it. Some are regular
I'm developing a plugin in Wordpress and am having difficulty trying to post data
I have been developing a plugin for Eclipse. The plugin has a couple of
I have an application I am developing that deploys a JAX-WS web service using
I'm currently developing a web application that will use Facebook as a authentication service.
Some websites now use a JavaScript service from Tynt that appends text to copied

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.