Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

java - Why getClass returns the name of the class + $1 (or $*)

I'm writing a piece of code in which I have to cast an Object if it is an instance of a certain class.

As usual I'm using instanceof for checking the compatibility.

The problem is that the check is never satisfied because the objects belong to "strange" classes.

For example; when I call the method getClass().getSimpleName() on this object it return me the name of the class + $* (e.g. ViewPart$1 instead of ViewPart).

What does this $* means? Is there a solution or a workaround?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That shows an inner class (either anonymous (if it has a number) or named). For example:

class Foo {
    static class Bar {
    }
}

The name of class Foo.Bar is Foo$Bar. Now if we had:

class Foo {

    static void bar() {
        Runnable r = new Runnable() {
            public void run() {};
        };

        System.out.println(r.getClass());
    }
}

That will print Foo$1.

You can see the same effect in the naming of the class files created by javac.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...