On Wed, 13 Feb 2002, Bryan Austad wrote:

> Date: Wed, 13 Feb 2002 10:23:58 -0700
> From: Bryan Austad <[EMAIL PROTECTED]>
> Reply-To: Tomcat Users List <[EMAIL PROTECTED]>
> To: Tomcat Users List <[EMAIL PROTECTED]>
> Subject: RE: Loading property files using ClassLoader.getSystemResource()
>
> Yes, I mean the getSystemResource is a static method.  I call this static
> method from another static method....
>
>    static public String formFullPath( String fName )
>    {
>       URL url;
>
>       if (fName.charAt(0) == '/'){
>          System.out.println("fName is " + fName);
>          return fName;
>       }
>       url = ClassLoader.getSystemResource(fName);
>       System.out.println("url is " + url);
>       return (url == null) ? fName : url.getFile();
>    }
>
> When I try using ClassLoader.getResource(fName), I get a compile error:
>
>     non-static method getResource(java.lang.String) cannot be referenced
> from a
>     static context
>
> How do I get around this?
>

One way is using the class loader that loaded your own class:

  public class Foo {

      static public String getBar() {

        URL url = Foo.class.getClassLoader().getResource("baz");
        ...

      }

      ...

  }

Another way is to use the class loader for your web application, if you're
running inside Tomcat:

        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        URL = cl.getResource("baz");

This technique has a particular advantage:  it will load the resource from
within /WEB-INF/classes or /WEB-INF/lib, even if the class you are calling
it from is loaded from a shared class loader (like the "lib" directory in
Tomcat).

Craig McClanahan



--
To unsubscribe:   <mailto:[EMAIL PROTECTED]>
For additional commands: <mailto:[EMAIL PROTECTED]>
Troubles with the list: <mailto:[EMAIL PROTECTED]>

Reply via email to