Return a string representing the name of the file expected to contain the source code for the specified object. - Java Reflection

Java examples for Reflection:Class Name

Description

Return a string representing the name of the file expected to contain the source code for the specified object.

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        Object object = "java2s.com";
        System.out.println(objectToSourceFileName(object));
    }/*from  w w w . ja  v  a2 s .  c  o m*/

    /** Return a string representing the name of the file expected to
     *  contain the source code for the specified object.  This method
     *  simply replaces "." with "/" and appends ".java" to the class
     *  name.
     *  @param object The object.
     *  @return The expected source file name.
     */
    public static String objectToSourceFileName(Object object) {
        String sourceFileNameBase = object.getClass().getName()
                .replace('.', '/');

        // Inner classes: Get rid of everything past the first $
        if (sourceFileNameBase.indexOf("$") != -1) {
            sourceFileNameBase = sourceFileNameBase.substring(0,
                    sourceFileNameBase.indexOf("$"));
        }

        return sourceFileNameBase + ".java";
    }
}

Related Tutorials