Reputation: 2144
I need to constant value from a java class but that class in a jar file. How to get that..
java class:
package com.user;
public final class Constants {
private Constants(){}
public static String NAME="name";
}
This class is present under "test.jar". i need to use this name from another repository. I don't want to use the dependency for this jar. I need to use directly.
How do I get this?
Upvotes: 1
Views: 1538
Reputation: 2144
I have fixed this using the following code.
Class.getField("NAME").get(null)
Refer: Accessing Java static final ivar value through reflection
Upvotes: 1
Reputation: 240
Actually it is really bad practice to do what you want to do. Why define a class but dont want to reference it on a classpath? Then maybe it shouldnt be a class. Also if you have constants like that it should be an enum in 99% of the time. If you REALLY want to do it your way, you still have to load the class manually using a Classloader (see the other comments for this).
But my guess is, you want to do some configuration or something? Then you propably want to use properties. Here is a simple example:
/* You should do real exceptionhandling here */
public static void main(String[] args) throws Exception {
final Properties config = new Properties();
try (final FileReader reader = new FileReader("config.properties")) {
config.load(reader);
}
System.out.println(config.getProperty("NAME"));
System.out.println(config.getProperty("com.stackoverflow.version"));
}
my file "config.propertes" is just a plaintextfile with the content:
# This is a comment
NAME=name
key2=somevalue
com.stackoverflow.version=9.87.6
You can also write a Properties object back into a file. You can use properties for a lot of stuff. Look at the Properties Javadoc for more information.
Upvotes: 1