Java set string as class name to run - java

I have a question, i have a code like below:
controller.start(c.class, 1);
but i want to set "c" from console. I can get/set it from args on main method . but how can i put it on c.class ? I mean how can i do that?
String a = "c";
controller.start(a.class,1);
Of course it doesnt work , but i hope i can tell u about my problem
On php we can use $$string to set/get string to variable, but i dont know how can we do it on Java ?

More commonly used (and more secure) way of addressing this is using maps:
private static final Map<String, Class<?>> NAME_TO_CLASS = new Map<>();
static {
NAME_TO_CLASS.put("c", c.class);
...
}
static void main(String[] args) {
...
controller.start(NAME_TO_CLASS.get(args[0]), 1);
}
Of course in real life you'd want to check if argument is correct and is in the map NAME_TO_CLASS.contains(your_arg);

Related

What's the Java equivalent of defining a classless object in JavaScript?

I'm wondering if I can declare an object in-line in Java like I can in JavaScript.
For example, in JavaScript I could say
let nameOfObject = {
anyKey: "my value",
someOtherValue: 5
};
console.log(nameOfObject.anyKey);// This logs "my value"
and this will create a classless object and assign nameOfObject as its "pointer" of sorts... How can I do this in Java? How do I create an object without a class?
I found one possible solution which looks like
Object nameOfObject = new Object(){
public String anyKey = "my value";
public int someOtherValue = 5;
};
System.out.println(nameOfObject.anyKey);
But that doesn't seem to compile, and says "anyKey cannot be resolved" and according to some other sources, will not work at all...
So I might be doing something very wrong, or maybe there's a different method, or maybe it's just straight up not possible with Java and I need to do it a different way...
class Some{
public String anyKey;
}
Some some = new Some() {
this.anyKey = "my value";
};
This code throws an error saying Syntax error, insert ";" to complete declaration, however
class Some{
public void anyMethod() {
}
}
Some some = new Some() {
public void anyMethod() {
System.out.println("Okay");
}
};
Works perfectly fine?
I don't understand what's going on here, but I would really appreciate an explanation and/or a solution (if one exists).
You can't really think of it as an "object" in Java. JavaScript objects are unique implementations of HashTables. If you want similar functionality, you can use a Java HashMap or ConcurrentHashMap(HashTable), depending on your specific requirements.
// we only add String->Double, but since you want to add "any type",
// we declare Map<Object, Object>
HashMap<Object, Object> map= new HashMap<>();
map.put("Zara", new Double(3434.34));
map.put("Mahnaz", new Double(123.22));
String[] names = map.keys();
while(names.hasMoreElements()) {
str = (String) names.nextElement();
System.out.println(str + ": " + map.get(str));
}
So, all objects in java have a class associated with them. Even raw Objects have a class: The Object class! You won't be able to create an object without a class because all values need to have a type of some sort. But that's really not a huge problem. If you need an object that stores certain values, you can just create a class that has space for those values. There's really no situation where you would not be able to do this.
That being said, if you just want a way of mapping keys to values, I'd recommend looking into the Map data structure.
JavaScript classes are different from Java classes, JavaScript is not a class-based object-oriented language, an object in JS is used as a template to hold properties, but in Java classes could hold variables (properties) and functions, so to initialize an object in Java there has to be a class for that object, you can think of it as a blueprint of how the object will be initiated for example to create a class:
public class Example {
public String link = "https://stackoverflow.com/";
public void printLink() {
System.out.println(link); // Prints the string stored in link
}
public void openLink() {
// Some code to open the link in the browser
}
}
To initialize an object from the class you created call this in your main or somewhere where the code will run:
Example example = new Example();
example.printLink(); // Printed the link
example.openLink(); // Opened the link
example.link = "https://example-link.com/"; // Changed the link
Note that the Example class could be in a different file and the file name has to be the same as the class name, here it is (Example.java)
Anyway if you are looking for an equivelant for JavaScript classes HashMap or HashTable could be very close.

"filed value" is coming like ‘1123456#lopoa’ format

If in java filed value is coming like 1123456#lopoa format.
So My question I am trying to take the value before #.
So according to java what to do to implement this logic?
You should use split(String) method of String class.
Following is working code:
public static void main (String[] args)
{
String val = "1123456#lopoa";
String[] vals = val.split("#");
System.out.println(vals[0]);
}
Output:
1123456
See it working here

Using scanner to create an object identifier?

Is there any way to create the name of an object depending on user input?
eg.
Object scan.nextLine() = new Object();
No it is not possible. There are no dynamic variables in Java. Java variable name have to be declared in the source code during compile time.
If want to store the Object with the user entered values you can try using a Map to save the data as below.
Map<String, Object> objects = new HashMap<String, Object>();
String name = scan.nextLine();
Object obj = new Object();
objects.put(name, obj); // saving the objects in Map
No you can't do this.
I would suggest having a custom class and store the instanceName:
public class MyClass {
private String instanceName;
public MyClass(String instanceName) {
this.instanceName = instanceName;
}
}
MyClass myObj = new MyClass(scan.nextLine());
No. You cannot do that in java. Since you should already have a class defined to create a object of it.
There are some ways you could fake doing this. You could use a map to give the perception of dynamically named Objects. But since you say you are a beginner, the short answer is no. Make sure you know what you are asking for in your example though. Your example is the equivalent of saying:
String line = "foo";
Object line = new Object();
My guess would be that's not what you wanted (and isn't possible).
Given the line
Type variable_name = expression ;
The name variable_name is simply used in the rest of the scope for referencing the outcome of expression. You know that Java is a compiled language, and these names are only useful to the programmer. Once the compiler does its job, it can use a translation table and replace those names with whatever ID it wants.
Since those name don't even exist at runtime, there's no way of choosing the name for a variable at runtime.
However you may need to access an object depending on user input (for example like in PHP variable variables $$a_var). Depending on your context, you may use reflection to access instance members, or a simple Map<String, Object>. Example with reflection:
public class VariableRuntime {
static class Person {
public String first, last, city;
}
public static void main(String[] args) throws Exception {
Person homer = new Person();
homer.first = "Homer";
homer.last = "Simpson";
homer.city = "Springfield";
System.out.println("What do you want to know about Homer? [first/last/city]");
String what = new Scanner(System.in).nextLine();
Field field = Person.class.getDeclaredField(what);
System.out.println(field.get(homer));
}
}
The same with a Map<String, String>:
public class VariableRuntime {
public static void main(String[] args) throws Exception {
Map<String, String> homer = new HashMap<String, String>();
homer.put("first", "Homer");
homer.put("last", "Simpson");
homer.put("city", "Springfield");
System.out.println("What do you want to know about Homer? [first/last/city]");
String what = new Scanner(System.in).nextLine();
System.out.println(homer.get(what));
}
}

When to use static initial block in JAVA?

Can anyone please explain me in which scenario we use static initial block?
You can use it as a "constructor" for static data in your class. For example, a common situation might be setting up a list of special words:
private static final Set<String> special = new HashSet<String>();
static {
special.add("Java");
special.add("C++");
...
}
These can then be used later to check if a string matches something interesting.
The most common scenario is loading some resources on class load, for example loading library for JNI
And another common one is when some of the code you need to use to create your statics throw exceptions.
Another example is java.lang.Object
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
...
I use them all the time to initialize lists and maps.
List<String> myList = new ArrayList<String>(){{
add("blah");
add("blah2");
}};
for(String s : myList){
System.out.println(s);
}

Can I print out the name of the variable?

I have created a no. of constant variables, more than 1000, those constants are unique integer.
public static final FOO 335343
public static final BAR 234234
public static final BEZ 122424
....
....
....
Is there a way to print out the FOO, BAR and BEZ, the variable of the names in Java?
I am not familiar with java reflection. I don't know if that helps.
if ( FOO == 335343)
---> output "FOO"
if ( BAR == 234234 )
---> ouptut "BAR"
....
Actually asking this question behind is that I want to write log into the file
say
System.out.println("This time the output is " + FOO);
and the actual output is
This time the output is 335323
I want to know which variable comes from 335323.
Is there any other way apart from putting those variable and its associate constant into hashMap?
Thanks
There are some 'special case' that u can have workaround for this (which is told by other), but the most important question is: why would you want to do this (printing out variable name)?
From my experience, 99.9% of similar questions (how to print variable name? how to get variable depends on user inputting variable name? etc) is in fact raised by beginner of programming and they simply have made incorrect assumptions and designs. The goal they are trying to achieve normally can be done by more appropriate design.
Edit
Honestly I still do not think what you are trying to do is the way to go, but at least I think the following is a workable answer:
It is more or less a combination of previous answer:
(Haven't try to compile but at least it give u an idea)
class Constants {
public static final int FOO = 123;
public static final int BAR = 456;
private static Map<Integer, String> constantNames = null;
public static String getConstantName(int constVal) {
if (constantNames == null) {
Map<Integer, String> cNames = new HashMap<Integer, String>()
for (Field field : MyClass.class.getDeclaredFields()){
if ((field.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) != 0) {
&& int.class == field.getType()){
// only record final static int fields
cNames.put((Integer)field.get(null), field.getName());
}
}
constNames = cNames;
}
return constantNames.get(constVal);
}
}
assuming you want to get a constant name, just do:
Constants.getConstantName(123); // return "FOO"
As I noted in my comment to the original post, I have a strong suspicion that the best solution for your current problem is to solve it in a completely different way. You seem to want to associate an int with a String, and one way to do this is to use a Map such as a HashMap. For e.g.,
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
Map<Integer, String> myMap = new HashMap<Integer, String>();
myMap.put(335343, "FOO");
myMap.put(234234, "BAR");
myMap.put(122424, "BEZ");
int[] tests = {335343, 234234, 122424, 101010};
for (int i : tests) {
// note that null is returned if the key isn't in the map
System.out.printf("%d corresponds to %s%n", i, myMap.get(i));
}
}
}
Edit 1:
Per your recent comments and update to your original question, I take it that you have many numbers and their associated Strings involved in this program and that your need is to find the String associated with the number. If so, then you need to think re-design, that the numbers and their strings should not be hard-coded into your program but rather be part of the program's data, perhaps in a text file with one column being the numbers and the next column (separated by a space perhaps), the associated text. This way you could read in the data and use it easily in a HashMap, or data base, or really any way that you desire. This will give your project much greater flexibility and robustness.
You can use something like:
for (Field field : MyClass.class.getDeclaredFields()){
if (field.getType().toString().equals("int")){
int val = (Integer)field.get(MyClass.this);
switch (val){
case 335343:
case 234234:
System.out.println(field.getName());
}
}
}
Remember to change MyClass for your class name and that at least one instance should exist to get the value of the field. So, if you are planning on testing the code in a main method, you should change MyClass.this to something like new Myclass().
Another thing to remember is that the fields are attributes and not method variables (so it won't work if you are using this to access variables declared inside a method).
You can use enum.
If these numbers just need to be unique, you can say
public enum Yourname {
FOO, BAR, BEZ
}
and refer to the name as Yourname.FOO and the value as Yourname.FOO.ordinal(). You can use enums for if-blocks, switch-statements.
If you want to have the numbers you gave in the question, so if FOO needs to be 335343, you can create numbered enums. Have a look at is-it-possible-to-assign-numeric-value-to-an-enum-in-java and number-for-each-enum-item.
I would suggest that you print out the line number, not the variable name. That should give you enough to determine where the message is coming from. Here's more info on how to do that:
How can we print line numbers to the log in java
I had a similar problem with a long list of int variables that I had to print the name of each variable and its value (main goal was to create a text file that was going to be imported in an Excel file).
Unfortunately I'm quite new in Java programming, so the only solution that I found (probably wrong) is to use two different arrays: one String array for the String name and another Int array for the corresponding values.
For example:
int varName01, varName02, ....
String[] listNames = new String {"varName01", "varName02", .....
int[] listValues = new int {varName01, varName02, .....
for (int i=0; i<listValues.length;i++)
{
print String.format("%s %d", listNames[i], listValues[i]);
}
Probably this is not the correct way to do it, so any opinion from some Java expert would be more than welcome. Thanks!

Categories