XML Feeds

.

[java-dev] adding a path to the classpath

topher lafata topher at topher.com
Mon Oct 8 11:28:13 MDT 2007


i don't think it was ever intended to be used that way but...
you could use reflection to call the method even though it
protected. good luck.
t


No look at reflection can be complete without talking about how to  
break one of the most sacred of all the rules in Java. Everyone knows  
that you cannot call a private method from outside of the class that  
defines it. Right? Well you can't if you stick to conventional  
techniques, but with reflection you can do darn near anything.

The first thing you need to call a private method is the Method  
instance that goes with the method you want to call. You can't get  
this from getMethod; it only returns public methods. The way to get  
hold of a private (or protected) method is to use getDeclaredMethod.  
While getMethod takes a client's view of a class and only returns  
public methods, getDeclaredMethod returns all of the methods declared  
by one class. In the example below, we use it to get at the Method  
object for the very private removeRange method on the  
java.util.ArrayList class:

       ArrayList list = new ArrayList();
       list.add("Larry");
       list.add("Moe");
       list.add("Curley");

       System.out.println("The list is: " + list);

       Class klass = list.getClass();

       Class[] paramTypes = { Integer.TYPE, Integer.TYPE };
       Method m = klass.getDeclaredMethod("removeRange", paramTypes);

       Object[] arguments = { new Integer(0), new Integer(2) };
       m.setAccessible(true);
       m.invoke(list, arguments);
       System.out.println("The new list is: " + list);
Once you have a private method, calling it is a simple matter of  
clicking off the final setAccessable safety and having at it:



On Oct 8, 2007, at 04:34 AM, guillaume wrote:

>
> hi all,
>
> i'm trying to add a temporary path to the classpath in the init  
> procedure of my application, but i can't manage to do it.
> the javadoc shows a "addDirectory" method for the MXJClassLoader  
> class, but it's protected. All i can do is getting the current  
> paths...
>
> Is there a way to do this?
>
> G.
>
> _______________________________________________
> java-dev mailing list
> java-dev at cycling74.com
> http://www.cycling74.com/mailman/listinfo/java-dev



More information about the java-dev mailing list