How to get the binary name of a java class, if one has only the fully qualified name?

后端 未结 3 2293
不思量自难忘°
不思量自难忘° 2021-02-19 07:01

The reflection classes and methods as well as class loaders etc. need the so called \"binary\" names of classes to work with.

The question is, how does one get the binar

3条回答
  •  不要未来只要你来
    2021-02-19 07:34

    A simple name omits a lot of information and it is possible to have many classes with the same simple name. That may make this impossible. For example:

    package stack;
    
    /**
     * 
     * @author Simon Greatrix
     */
    public class TestLocal {
    
        public Object getObject1() {
            class Thing {
                public String toString() { 
                    return "I am a Thing";
                }
            }
            return new Thing();
        }
    
        public Object getObject2() {
            class Thing {
                public String toString() { 
                    return "I am another Thing";
                }
            }
            return new Thing();
        }
    
        public Object getObject3() {
            class Thing {
                public String toString() { 
                    return "I am a rather different Thing";
                }
            }
            return new Thing();
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            TestLocal test = new TestLocal();
            Object[] objects = new Object[] {
                    test.getObject1(),                
                    test.getObject2(),                
                    test.getObject3()                
            };
    
            for(Object o : objects) {
                System.out.println("Object      : "+o);
                System.out.println("Simple Name : "+o.getClass().getSimpleName());
                System.out.println("Name        : "+o.getClass().getName());
            }
        }
    }
    

    This produces the output:

    Object      : I am a Thing
    Simple Name : Thing
    Name        : stack.TestLocal$1Thing
    Object      : I am another Thing
    Simple Name : Thing
    Name        : stack.TestLocal$2Thing
    Object      : I am a rather different Thing
    Simple Name : Thing
    Name        : stack.TestLocal$3Thing
    

    As you can see, all three local classes have the same simple name.

提交回复
热议问题