JMF Format checking: The Evil Edition

Desperate times sometimes require desperate solutions for stupid problems. For example today I have a deadline for a small JMF project. A part of the project is, that an RTSP client should be able to request only for example the audio streams of a certain object on the server so the client should have some kind of flag that specifies what streams should now really be used.


But what happens, when you have an MP3 file and the user requests “video-only”-playback? Should really the player try to SETUP the whole thing or should it just be able to determine based on the server’s response to a RTSP call wether there even is a video stream? I would say so, yes, but there comes the next big problem right around the corner: From what I’ve seen of JMF so far, you can just simply pass something like “MPEG/RTP” into an javax.media.Format class and determine from this wether or not this is an audio or a video stream.

So now back to the desperate solutions thing: Format has two subclasses for handling Audio and Video formats … AudioFormat and VideoFormat. Both of them have a bunch of constants that store strings like “MPEG/RTP” ;-) And Java has some nice reflection-abilities. I guess that code was inevitable:

private static boolean checkFormat(String input,Class formatClass){
	for(Field f : formatClass.getDeclaredFields()){
		int m = f.getModifiers();
		Object v;
		if (Modifier.isFinal(m) && Modifier.isStatic(m)){
			try {
				v = f.get(
					formatClass.getConstructor(String.class).newInstance("")
					);
				if (v instanceof String){
					if(((String)v).toLowerCase().equals(input.toLowerCase())){
						return true;
					}

				}
			}
			catch(Exception e){};
		}
	}
	return false;
}

This little method does one thing: It searches all the String constants of the given class for one with the value that is the same as the other input parameter.

So you can now do something like this:

checkFormat("MPEG/RTP",javax.media.format.VideoFormat.class));

… and get true. Probably a stupid solution, but at least it works ;-)