Created
January 3, 2025 11:11
-
-
Save SylvainJuge/62d66fa71af017661075d57b0080b24f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// toggle comment to test with/without package | |
package com.mycompany; | |
public class Main { | |
private static final boolean DEBUG = false; | |
public static void main(String[] args){ | |
printClass("regular class",MyClass.class); | |
MyClass anonymous = new MyClass(){ | |
public void myMethod(){} | |
}; | |
printClass("anonymous class",anonymous.getClass()); | |
printClass("primitive type", int.class); | |
MyClass lambda = ()->{}; | |
printClass("lambda", lambda.getClass()); | |
// arrays are a possible corner case but unlikely to be used to invoke methods | |
// | |
// printClass("array of regular class", MyClass[].class); | |
// printClass("array of primitive type", int[].class); | |
} | |
private static void printClass(String desc,Class<?> type){ | |
System.out.println("-- "+desc); | |
if(DEBUG){ | |
print("Class.getName()",type.getName()); | |
print("Class.getSimpleName()",type.getSimpleName()); | |
Package pkg = type.getPackage(); | |
String pkgString = "n/a null package"; | |
if(pkg != null){ | |
pkgString = pkg.getName(); | |
} | |
print("Class.getPackage().getName()",pkgString); | |
print("Class.getPackageName() (java9+ only)",type.getPackageName()); | |
print("Class.getCanonicalName()",type.getCanonicalName()); | |
System.out.println(""); | |
} | |
System.out.println("code.namespace = "+type.getName()); | |
String functionName = "n/a, not available for primitive types"; | |
if(!type.isPrimitive()){ | |
try { | |
functionName = type.getMethod("myMethod").getName(); | |
} catch (Exception e){ | |
throw new RuntimeException(e); | |
} | |
} | |
System.out.println("code.function.name = "+functionName); | |
System.out.println(""); | |
} | |
private static void print(String method, String v){ | |
System.out.printf("method %s '%s'%n",method,v); | |
} | |
} | |
public interface MyClass { | |
public void myMethod(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment