This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Understanding how this code works Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Understanding how this code works" Watch "Understanding how this code works" New topic

Understanding how this code works

jorge Garcia

Joined: Jan 09, 2008
Posts: 16
I built a class to play a sound wav file and I had some trouble getting it to work from a jar file.

I found this code online and it solved my problem but I just don't get what it's doing.

This is the: in= this.getClass().getResourceAsStream("/audio/Bell.wav");

I don't see what 'this.getClass() is doing exactly? 'in' is an InputStream object so is 'this.getClass()' getting an instance of the class vs. getting an object?

Here is the full class code:

import javax.sound.sampled.*;

public class SoundTest {

//variable declaration

AudioInputStream stream;
AudioFormat format;
Clip clip;
DataLine.Info info;
InputStream in;

public static void main(String[] args) {

SoundTest soundtest = new SoundTest();


public void go() {

in= this.getClass().getResourceAsStream("/audio/Bell.wav");
}catch(Exception e) {}

try {
stream = AudioSystem.getAudioInputStream(in);
} catch (Exception e) {}

format = stream.getFormat();
info = new DataLine.Info(Clip.class,format);

clip = (Clip) AudioSystem.getLine(info);;
System.out.println("Start is next");
System.out.println("Line after Start");
System.out.println("Line after Thread-Sleep");
} catch (Exception a) {}

}//close go

}//close class
Bill Shirley
Ranch Hand

Joined: Nov 08, 2007
Posts: 457
this is a reference to the current object you are executing code within,

getClass() is the class object it is an instance of

MyClass.class.getResourceAsStream("..."); // just about the same

Bill Shirley - bshirley -
if (Posts < 30) JavaRanchFAQ);
jorge Garcia

Joined: Jan 09, 2008
Posts: 16
Thanks, Bill. I got it now, the object is a class.
I agree. Here's the link:
subject: Understanding how this code works
It's not a secret anymore!