static class PushConfig{
#Value("${jpush.mq.appKey}")
private String appKeyMQ;
}
like this, I want to get config in inner Class,it's not work
Create a new class with this code:
public static anyName = yourClass
Then you can use anyName.anyMethod(...) to use a method
Related
I have a big class containing a lot of definitions.
Is there a way to move/create/extract a structure using IntelliJs build in features?
So i can keep the references to those fields without having to add qualifiers for all usages?
Current is case:
public static class Tables {
public final static String METADATA_CREATE_TS = "create_ts";
public final static String TABLE_1_ID;
public final static String TABLE_1_NAME;
public final static String TABLE_1_INTERNAL_ID;
public final static String TABLE_1_CUSTOMER_ID;
.
.
.
public final static String TABLE_N_ID;
}
How it should look like:
public static class Tables {
public final static String METADATA_CREATE_TS = "create_ts";
public static class Table1 {
public final static String TABLE_1_ID;
public final static String TABLE_1_NAME;
public final static String TABLE_1_INTERNAL_ID;
public final static String TABLE_1_CUSTOMER_ID;
}
}
Create the inner class.
Go to class Tables --> right click --> move members
Mark the fields that you want to move.
In To write the inner class name (...Tables.Table1)
Click Refactor
This is doable with a little bit of trickery.
You can use F6 in IntelliJ to move a set number of fields to a new class. After you created the new class you can than select all of the newly created classes and press F6 again to make all of those classes an inner class of a different class, which solved my overall goal.
Need a variable to hold a value which will be assigned once and will be used by every method of a class
if I specify it as non static variable it is not holding the value
Class Test{
private String test;
public void method1(){
test = "String1";
}
public void method2(){
System.out.println(test.length());
}
}
Getting Null Pointer exception. the value of the test will be used in every method.
Could anyone help me, how to fix the issue.
The NullPointerException will be thrown whenever the test variable is null and you try to invoke methods on that variable. In your case, when you invoke method2() before method1(). That has nothing to do with global, local or whatever, as Long Vu already mentioned.
So first you should make sure, you don't access an uninitialized variable. Then, if you need a class with a single instance, which should be accessible application wide, you can implement this using the singleton pattern. For more about it, have a look at this Wikipedia page: https://en.wikipedia.org/wiki/Singleton_pattern
Maybe your problem is that you are creating multiple objects of class Test.
For example this should work:
Test test1=new Test();
test1.method1(); //call this first then other methods
test1.method2();
You should use this object "test1" as a parameter wherever you need it.
If you want to access the variable globally then create a Singletone class:
class Test{
private static Test single_instance = null;
private String test;
// private constructor restricted to this class itself
private Test(){
}
// static method to create instance of Singleton class
public static Test getInstance(){
if (single_instance == null)
single_instance = new Test();
return single_instance;
}
public void setTest(String value){
test = value;
}
public String getTest(){
return test;
}
public static void main(String args[]){
Test test = Test.getInstance();
test.setTest("String1");
test.getTest();
}
}
I have a variable which is initialize in one class and i want to use it in another java class
and i want to use collect as table name in another class which is for Database Helper class how can i do it..
Thanks in advance for making a time to read it :)
i have a example code below
public class example()
{
String collect;
//and here i have one spinner
//and in itemSelected in spinner
//i getting that item like this
String item = getItemslected.toString;
collect=item;
}
Options:
1.Use static variable:
Declare static String collect;
and access it from other class as <YourClassNmae>.collect;
where YourClassName is the class in which you have declared the static variable.
2.Use Application class
Create application class extending Application
public class MyApplication extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
Declare the application class name in manifest like:
<application
android:name=".MyApplication"
android:icon="#drawable/icon"
android:label="#string/app_name">
Then in your activities you can get and set the variable like so:
// set
((MyApplication) this.getApplication()).setSomeVariable(collect);
// get
String collect = ((MyApplication) this.getApplication()).getSomeVariable();
You can declare that variable as public static and you can use it from any other class. Other way to use that is by using set and get method.
You can make a variable static and refer to it using Classname.variable. If you don't want to make it static, you'll need a reference to an instance of the class then refer to it using myInstance.variable. The other option is to use methods to return it (again, either static or non-static).
The variable (or method) will also need the appropriate access modifier:
https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
public class Main{
public static void main(String[] args) {
System.out.println(Example.test);
Example.test = "123";
System.out.println(Example.test);
}
}
public class Example{
public static String test = "This is a Test";
}
Output:
This is a test
123
I'm trying to initialize a static class, with an argument, and then run some more static code in that class.
I'm aware of the static block, but it seems it can't take any arguments.
Is there a way to pass arguments to a static constructor?
If not, what is the recommended technique to initialize a Static class using an argument?
Edit:
A static class to my understanding is a class which cannot be instantiated (in c# they're called static classes, if Java has a different term for them, sorry for not being aware of it) - it's accessed through it's class name rather than an object name.
What I'm trying to achieve (very simplified) is a class which receives a dictionary as String, parses it, and has methods manipulate it like GetRandomEntry.
Here's an elaborated snippet of my code:
public class QuestionsRepository {
private static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();
//...
staticĀ
{
// need to receive and parse dictionary here
}
//...
Taking the relevant parts of a code snippet is never easy, hope i have chosen wisely (:
Another detail that may be relevant - I'm a c# programmer, usually. Just Started learning Java lately.
Thanks.
I think you would need to initialize the static fields of the class according to some input. You can do it in the following way by calling the static method of another class:
class ClassToInitialize {
static {
staticField = ParamPassClass.getParameter();
}
private static String staticField;
ClassToInitialize() {
System.out.println("This is the parameter: " + staticField);
}
}
class ParamPassClass {
private static String parameter;
static String getParameter() {
return parameter;
}
static void setParameter(String parameter) {
ParamPassClass.parameter = parameter;
}
}
class Main {
public static void main(String args[]) {
ParamPassClass.setParameter("Test param");
new ClassToInitialize();
}
}
Java doesn't have static constructors. It only has static initializers and static initializers do not take any arguments. It is executed when the class is first loaded, and there is no way to call it yourself.
You either need to use actual objects, or add some way of configuring the class (eg through a static method).
you should mention the member class with a static qualifier, otherwise there is no such a thing as a static class
Here you can find the explanation of using the word 'static' in this context.
Now you should just call its constructor and pass all the arguments you want,
the only restriction that you have on a static member class is that it can't refer the non-static fields of its outer class, it resembles a static methods on class that can't refer the non-static fields of class.
I didn't understand why do you mention a static initialization block here, could you please clarify a little?
Be aware also that in java there is no such a thing as static constructor....
Hope this helps
You can have a static method public static void setUp(Arg1 arg1, Arg2 arg2...) which sets up all your static fields and invoke it when your program starts.
You have to make sure this method will be called only once [or only when you want to reset these fields]
It is not possible to pass arguments directly to the static initializes (JLS:static initializers).
It would be nice if you could share more information about your goals.
You could use an enum to initialize a singleton with a string parameter like this
import java.util.*;
class Data {
static Map<String,String[]> easyDefinitions = new HashMap<String,String[]>();
}
public enum QuestionsRepository
{
repository("primary=red,green,blue;secondary=cyan,yellow,magenta");
QuestionsRepository(String dictionary) {
String[] rules = dictionary.split(";");
for (String rule:rules) {
String[] keyValuePair = rule.split("=",2);
Data.easyDefinitions.put(keyValuePair[0],keyValuePair[1].split(","));
}
}
}
I use an java application which generates a class dynamically. Via an ant script the source code will be produced for a give classname and a class template.
In the template for the class I need to know the name of even this class, to call a static method of the class.
Example. The class will be named "VersionInfo". Then in static main() of it I want to call the static method: VersionInfo.getId().
But I don't know the class-name.
Is there an equivalent to "this" for static contexts or some Utility-Class for such a purpose?
If you are creating the class via Ant then why not just generate a static method getClassName that returns the name of the class?
If your main method resides in the same class you just can call getId() in the main method.
So you're saying that it should generate this?
public class VersionInfo{ // VersionInfo class name changes, per problem description
public static void main(){
System.out.println(getId());
// but in the main within the class,we don't need the classname to call a static method
}
public static string getId(){
return "what's the problem?";
}
}
Is there something missing from the description, that you're calling some OTHER class' static method by an unknown-to-the-template name?
There's a nasty workaround:
public static final Class THIS_CLASS = new Object() {
public Class getParentClass() {
return getClass().getEnclosingClass();
}
}.getParentClass();
I'm not sure I understand. If you generate the class VersionInfo yourself, why can't you get the class name from the code that generates the class?
Try this:
package uk.co.farwell.stack_overflow;
public class Test_847708 {
private final static String getId() {
return "string";
}
public static void main(String args[]) {
System.out.println("getId=" + getId());
}
}
You cannot use the key "this" in a static context.
Instead, if you want to call dynamically a static function, you can use java reflection.
I cannot help you further for java reflection because I never use it, but I already use it in .Net and it's a powerful tools.
The cleanest answer to the question might be to make a third class with a static, known, name that is generated by the ANT script which references the dynamic class name, and then have your main method reference that known class.
If for some reason that isn't enough, then combine Joachim Sauer and Melursus answer, and get the class name, and then get the method via reflection:
Method m = THIS_CLASS.getDeclaredMethod("getId", null);
Object result = m.invoke(null, null);