简体   繁体   中英

How do i access a static member from my own custom class loader?

I have created my own custom class loader for loading a class to JVM. i can access the non static members using following code

MyLoader c=new MyLoader();
Class cls=c.loadClass("Hello");
Object obj=cls.newInstance()
cls.getMethod("show").invoke(obj);

But i don't know the procedure for accessing a static memebrs of a loaded class. Kindly provide a solution for this problem.

If you have static class members, you can access them just exactly calling from Class Class.myStaticMemeber . Static members also are called Class member, as you can call them directly from the class. Of course you can call them using the instance too, such as cls.myStaticMember , but you should remember that changing value of static member in one place will make this change to all places where you have called that static member.

// String.class here is the parameter type, that might not be the case with you
Method method = clazz.getMethod("methodName", String.class);
Object o = method.invoke(null, "whatever");

In case the method is private use getDeclaredMethod() instead of getMethod() . And call setAccessible(true) on the method object.

for static methods we can use null as instance of class

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.

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