Mathews Mathai Mathews Mathai - 21 days ago 5
HTML Question

Java Applet Commented Applet Tag

I am new to applets and came across something unusual. In one of the programs I went through,

applet html tag
is mentioned as a comment in the
Applet Java file (.java)
but the comment seems to be getting executed. How is this possible?

Code:

import java.awt.*;

import java.applet.*;

/*<applet code="MyApplet" width=100 height=50></applet> */ 

//why we give comment here and how it is executed ??

class MyApplet extends  Applet
{
 public void paint(Graphics g)
{
g.drawString("A Simple Applet",100,100);

}
}


Comment:
/*<applet code="MyApplet" width=100 height=50></applet> */ 



How is the above comment getting executed? Aren't comments meant to be skipped?


Why is this method not mentioned on Oracle or any other websites?
Even Oracle asks to create seperate HTML file. So does this method use some 3rd party library to execute the comment?

I am also getting an error when I don't make the class public and when I keep the file and class name different.

Can someone please explain this method? I googled a lot but an explanation for this method of including the tags in a comment is nowhere to be found. There is a post on SO but the answer is not up to the point. Please Help.

How could someone accidentally figure out that this is possible? Is this any particular feature of the Applet Class?

Answer

But how does it override the usual mechanism of skipping the comment lines?

You're thinking the compiler, not the applet viewer. Different tools that work in different ways.

Does it parse comments too?

AFAIU the applet viewer only parses the Java source code (note, source code, not the binary) up to the class definition. By design it ignores any code that is not in a comment and inspects only the commented code for possible applet tags. This new functionality was introduced around Java 1.7 or 1.6 AFAIR.

I didn't get this point -'By design it ignores any code that is not in a comment'. Does this mean it only looks for comments and then further selects the comments with applet tag?

Sorry, now you repeat it back to me, it is unclear. "Does this mean it only looks for comments and then further selects the comments with applet tag?" Yep. And thanks, that's a much better way to express what I meant.

I'll close by adding some comments by @zakki that I think are too informative to be hidden in a comments section:

@zakki: I think appletviewer MyApplet.java parses MyApplet.java as HTML, and it ignores unsupported elements like import java.awt.*;. AppletViewer Tags

@zakki: It seems that appletviewer just process input as token stream ant it doesn't care java/html syntax. gist.github.com/zakki/b5176a7d37fa3938f0646d11d9bd01a5

Comments