How to Get Package Name of Source Class File in Android ?

前端 未结 5 2195
礼貌的吻别
礼貌的吻别 2020-12-17 18:55

I am using only one project to port lite and full versions for that I am just updating Manifest file package names.

My project structure is like this

My Ap

相关标签:
5条回答
  • 2020-12-17 19:33

    The Kotlin solution:

    val packageName = this.javaClass.`package`?.name
    
    0 讨论(0)
  • 2020-12-17 19:48

    Might Be helpfull

    package org.kodejava.example.lang;
    import java.util.Date;
    
    public class ObtainingPackageName {
    public static void main(String[] args) {
        //
        // Create an instance of Date class, and then obtain the class package
        // name.
        //
        Date date = new Date();
        Package pack = date.getClass().getPackage();
        String packageName = pack.getName();
        System.out.println("Package Name = " + packageName);
    
        //
        // Create an insatnce of our class and again get its package name
        //
        ObtainingPackageName o = new ObtainingPackageName();
        packageName = o.getClass().getPackage().getName();
        System.out.println("Package Name = " + packageName);
       }
    } 
    
    0 讨论(0)
  • 2020-12-17 19:49
    String packageName = this.getClass().getPackage().getName();
    

    will work definitely.

    0 讨论(0)
  • 2020-12-17 19:53

    try this,

        try {
            Class c = Class.forName("package_name.MyClass");
    
            Object o = c.newInstance();
    
            Package p = o.getClass().getPackage();
    
            System.out.println("Package Name :: " + p.getName());
    
        } catch (ClassNotFoundException e) {            
            e.printStackTrace();
        } catch (InstantiationException e) {            
            e.printStackTrace();
        } catch (IllegalAccessException e) {            
            e.printStackTrace();
        }
    
    0 讨论(0)
  • 2020-12-17 19:57

    Simple example of some class NotificationListener:

    Timber.d(NotificationListener.class.getPackage().getName());
    Timber.d(NotificationListener.class.getSimpleName());
    Timber.d(NotificationListener.class.getName());
    

    Output:

    D/PermissionsUtil: com.example.receivers
    D/PermissionsUtil: NotificationListener
    D/PermissionsUtil: com.example.receivers.NotificationListener
    
    0 讨论(0)
提交回复
热议问题