Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java getResourceAsStream static workaround. Correct?

I was using this code to get my resources:

 this.getClass().getResourceAsStream("Image.png");

it worked fine up until the point where I had to implement it in a static method:

 public class UserDisplay {

 public static void PlayerWon(final Display display, String player, final Composite WinCompo){

I could not use the this keyword in static context so I used the object I previously initialized:

public class UserDisplay {

 public static void PlayerWon(final Display display, String player, final Composite WinCompo){

    final AudioLoop WinLoop = new AudioLoop("Sound.wav");

    final Image WinBanner = new Image(display, WinLoop.getClass().getResourceAsStream("Image.png"));

It works fine, but here is my Question:

Is this a legitimate workaround? If not, what should I have done?

Note: I apologize for the poor Title.

like image 902
James Allison Avatar asked Oct 24 '25 02:10

James Allison


2 Answers

Use a class literal instead. It's not clear what AudioLoop is in this case, but unless it's a class in your own library, that's probably not what you want. I suspect you want something like:

new Image(display, UserDisplay.class.getResourceAsStream("Image.png"))

If you do want to get a resource relative to the AudioLoop class, use:

new Image(display, AudioLoop.class.getResourceAsStream("Image.png"))

Also note that your method and variable names don't currently comply with Java naming conventions, where both would normally be camelCased.

like image 92
Jon Skeet Avatar answered Oct 25 '25 17:10

Jon Skeet


Use the UserDisplay.class.getResourceAsStream("Image.png"). You are getting a reference to the same class just in a different way.

like image 38
Saket Avatar answered Oct 25 '25 16:10

Saket