Java getting package name

Get / Find Package Name Of Java Class

In this tutorial, we are find / get the package name of a Java class by providing the class name using java API.

Package packs = str.getClass().getPackage();

On above code we are using object.getClass().getPackage() method for getting the package name.

Find Package Name Of Java Class

public class FindPackageName

//Find package name of a class
public static void main ( String [] args )

// Get package name of String class
String str = new String () ;
Package packs = str.getClass () .getPackage () ;
String packageName = packs.getName () ;
System.out.println ( «Package Name java10″>+ packageName ) ;

// Find current class name package
FindPackageName o = new FindPackageName () ;
packageName = o.getClass () .getPackage () .getName () ;
System.out.println ( «Package Name java10″>+ packageName ) ;
>
>

Output
Package Name = java.lang Package Name = com.examples

Find Package Name Of Current Java Class

If you need to append class name with package name, then you need to use this.getClass().getCanonicalName() by replacing this.getClass().getPackage()

public class FindPackageNameOfCurrentClass

// Find current package name of a class
public static void main ( String [] args ) FindPackageNameOfCurrentClass fpnc = new FindPackageNameOfCurrentClass () ;
System.out.println ( «current package name java10″>+fpnc.getCurrentPackage () .getName ()) ;
>

private Package getCurrentPackage () return this .getClass () .getPackage () ;
>
>

Output
current package = name com.examples

Источник

How to find the package name given a class name?

Given a class name as a string, how do I get the package name of it at run time ? I do not have the fully qualified name with package name + class name. Simply only the class name. I want the package name to be used in Class.forName() method. I am perfectly fine with finding the first matching package name (if multiple packages have the same class). Any ideas? UPDATE I DO NOT have a Class instance to work on. My requirement is to create a Class using the Class.forName() method. But I simply have ONLY the class name as a string. I need some way to loop though the packages and identify if the class I have belongs to the package. The stack trace of the exception is

Exception in thread "main" java.lang.ClassNotFoundException: MyAddressBookPage at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:169) 

Why are you voting everyone down? We are just trying to help. If everyone is giving similar answers then it means that you were not able to describe your problem well and its your fault in the first place..

Читайте также:  Android project run as java application

An example of what you mean in terms of class name vs fully qualified class name may be useful in clearing up the confusion, e.g. «I only have ‘Baz’, I don’t have ‘com.foo.bar.Baz’.

@Cemre, it’s not him, it’s me. I’m voting them down because they’re not answering his question. Don’t take it personal! 🙂 Once they’re edited to be useful answers I’ll go back and remove the downvote where it doesn’t apply anymore. But currently, they’re just not good answers. That’s how we start the journey from no answer, to best answer on the web. Again, don’t take it personally.

sorry for misunderstanding. It’s a bit intimidating to see my already low reputation go down. @Grundlefleck thanks for replying. 😉

Источник

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

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 App
|_src
|_com.example.myapp
|_MyClass.java and my Manifest package name is different. package=»com.example.myapplite» I am using one library project in that I want package names of classes that I am using in MyApp. I have used this

 System.out.println("Package Name " + context.getPackageName()); 

But its giving me a Manifest file package name value ie. com.example.myapplite I want MyClass.java package name. ie. com.example.myapp Also I am aware about this

 MyClass mClass = new MyClass(); Package pack = mClass.getClass().getPackage(); 

But I can’t use this approach because I am using following approach to get class file in my library project

Class c = Class.forName("package_name.MyClass"); 

It’s not clear why you’d use new MyClass().getClass() (effectively) rather than just MyClass.class . or why that’s not enough for you. Your explanation of using Class.forName doesn’t really explain what you’re trying to do. What do you wish you could do that Class.getPackage() doesn’t do for you?

I am using library project, to use MyClass in my library project I need to access it Class.forName(«package_name.MyClass»); because library project dosent aware about MyClass.java

5 Answers 5

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 mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
)">edited Feb 15, 2013 at 7:09
Vinay
6,8934 gold badges32 silver badges50 bronze badges
answered Feb 15, 2013 at 7:06
3
    I using library project so I cant create object of MyClass before accessing it. I am using Class.forName("package_name.MyClass"); to access that class for that I need package name.
    – Mac
    Feb 15, 2013 at 7:12
    1
    Be aware that Class.getPackage() can return null if the class loader for the class does not register the package. This is typically done from within the ClassLoader by using ClassLoader.definePackage(). You can see this in action in for example URLClassLoader. If you're not installing a custom ClassLoader, you shouldn't have any problem as the default ClassLoader will define packages while loading classes.
    – Timmos
    Oct 2, 2014 at 9:59
    What's the output?
    – winklerrr
    Mar 24, 2017 at 17:19
Add a comment|
5

The Kotlin solution:

val packageName = this.javaClass.`package`?.name

Источник

How can I get package name in android?

I need to write some util class by myself and I need the packagename of android app. While I found the packageManager which only can be used in Activity and so on that has context. I only want to get packagename in my class which will be used in android app. So how can I do this? Thank you!

9 Answers 9

Use : getPackageManager().getPackageInfo(getPackageName(), 0).packageName Or just MyContext.getPackageName()

You can also create a function:

public String getPackageName(Context context)

thank you,maybe I didn't describe clearly,It's an ordinary class,so it hasn't Context.The class will be packaged in a jar which used in android app.So I can't get method to reach it.

The following constant is available without the need for a context.

BuildConfig.APPLICATION_ID 

you can get the package name of installed app:

ArrayList res = new ArrayList(); PackageManager pm = getApplicationContext().getPackageManager(); List packs = pm.getInstalledPackages(0); 

and if you want to find the package name of your app:

thank you,maybe I didn't describe clearly,It's an ordinary class,so it hasn't Context.The class will be packaged in a jar which used in android app.So I can't get method to reach it.thank you all,but all of your answer is same.

getApplicationContext().getPackageName() will give the package name.

why? Always give the reason if you are asked someone not to use it. I also don't know why you asked not to use this.

This will retrieve the wrong package name. See my answer below to always get the correct java package name. Your answer can be modified by gradle thus producing “inaccurate” package names (I.e. it’ll say debug, release, or whatever build flavor you have set up)

List packages; PackageManager pm; pm = getPackageManager(); get a list of installed apps. packages = pm.getInstalledApplications(0); ActivityManager mActivityManager = (ActivityManager) context .getSystemService(Context.ACTIVITY_SERVICE); for (ApplicationInfo packageInfo : packages) < //packageInfo.packageName contains package name >

thank you,maybe I didn't describe clearly,It's an ordinary class,so it hasn't Context.The class will be packaged in a jar which used in android app.So I can't get method to reach it.thank you all,but all of your answer is same.

you can create a Util Class this way:

then you can use it this way

public class MyActivity extends Activity < @Override public void onCreate(Bundle bundle)< . AppInfo.init(getApplicationContext()); . >> 

then you can call it this way:

I have seen the following two ways to get the package name starting from a Context variable:

context.getPackageManager().getPackageInfo(context.getPackageName(), 0).packageName 

Won't they always give the same answer? Is one way preferable to use over the other in certain circumstances?

Here add this to your util class. It makes sure to handle different “flavors” and debug/release builds, as other answers do not:

@Nullable public static String getApplicationPackageName(@NonNull Context context) < final PackageInfo packageInfo = getPackageInfo(context); if (packageInfo.applicationInfo == null) < return null; >// Returns the correct “java” package name that was defined in your // AndroidManifest.xml. return packageInfo.applicationInfo.packageName; > // Convenience method for getting the applications package info. @NonNull private static PackageInfo getPackageInfo(@NonNull final Context context) < final PackageManager packageManager = context.getPackageManager(); try < return packageManager.getPackageInfo(context.getPackageName(), 0); >catch (final PackageManager.NameNotFoundException ignored) < //noinspection ConstantConditions: packageInfo should always be available for the embedding app. return null; >> 

Источник

Оцените статью