Accessing Number value of one class in other static class - java

Accessing the FileType values in converterfactory. I have a class named FileType:
public final class FileType
{
public static final FileType VALUES[];
public static final FileType WORD;
static
{
WORD= new FileType("WORD", 0);
VALUES = (new FileType[] { WORD});
}
public static final FileType[] values()
{
return (FileType[])VALUES.clone();
}
String s;
int i;
private FileType(String msofficedoC, int i) {
this.s= msofficedoC;
this.i=i;
}
}
I have a another class ConverterFactory in which I want to access the number of MSOFFICEDOC as 0 so I have _cls1 class.
static class cls1
{
static final int SwitchMapfile2xliff4jFileType[];
static
{
SwitchMapfiletoxliffFileType = new int[FileType.values().length];
try
{
SwitchMapfiletoxliffFileType[FileType.WORD.ordinal()] = 1;
}
catch(NoSuchFieldError nosuchfielderror) { }
}
}
In FileType.WORD.ordinal() it is giving an error but I want to access FileType.WORD value in switch case
switch(cls1.SwitchMapfiletoxliffFileType[filetype.i])
{
case 1:
}
It is giving an exception
Exception in thread "AWT-EventQueue-0"
java.lang.ExceptionInInitializerError
please give me some suggestion this .
Thank you in advanced

Related

How do I execute the function public method declared inside a class which is in turn inside a private method?

So, I want to execute the sum() of the following block of code:
import java.lang.reflect.Method;
public class LocalOuterClass { // start of outer
private int x = 10;
private Object run() { //start of inner
class LocalInnerClass {
private int y = 20;
public void sum() {
System.out.println(x+y);
}
} //end of inner
LocalInnerClass lc = new LocalInnerClass();
//lc.sum();
return lc;
}
public static void main(String[] args) {
LocalOuterClass Loc = new LocalOuterClass();
Object obj = Loc.run();
System.out.println(obj.getClass());
Method[] methods = obj.getClass().getMethods();
for (Method method : methods) {
String MethodName = method.getName();
System.out.println("Name of the method: "+ MethodName);
}
}
} //end of outer
When I do lc.sum(), the sum() is correctly executed. But when I'm returning an object of the inner class to the main() and try to execute sum(), it gives a compiler error. Doing getClass().getMethods() on the object does print sum() as one of the methods. What should I do to execute the sum() inside main()?
You have to change return type to LocalInnerClass and move LocalInnerClass out of the method:
public class LocalOuterClass {
private int x = 10;
private class LocalInnerClass {
private int y = 20;
public void sum() {
System.out.println(x + y);
}
}
private LocalInnerClass run() {
LocalInnerClass lc = new LocalInnerClass();
//lc.sum();
return lc;
}
public static void main(String[] args) {
LocalOuterClass Loc = new LocalOuterClass();
LocalInnerClass obj = Loc.run();
obj.sum(); // it works!
// ...
}
}
The problem is, that the whole LocalInnerClass is not known to your main-method. It does not help, that it has a public method, if the whole type is unknown. You need to refactor your code in order to change that.
Actually your method run currently returns a value of type Object and you'd need to return a value of type LocalInnerClass, however this is not possible due to type visibility.
There are basically two options you have. One is to move the whole LocalInnerClass to a location that is visible to main (like oleg.cherednik suggested):
class LocalOuterClass {
private int x = 10;
private LocalInnerClass run() { // now we can retun `LocalInnerClass`
return new LocalInnerClass();
}
public static void main(String[] args) {
new LocalOuterClass().run().sum(); // works!
}
private class LocalInnerClass {
private int y = 20;
public void sum() {
System.out.println(x+y);
}
}
}
Another option is to implement/extend a different type that has sum, e.g. like this:
class LocalOuterClass {
private int x = 10;
private Summable run() { //start of inner
class LocalInnerClass implements Summable {
private int y = 20;
public void sum() {
System.out.println(x+y);
}
}
return new LocalInnerClass();
}
public static void main(String[] args) {
new LocalOuterClass().run().sum(); // works as well
}
private interface Summable {
void sum();
}
}
With this interface-option the type LocalInnerClass is still not visible to anyone outside your run-method, however the Summable-interface is and since your LocalInnerClass implements Summable you can return a value of that type.

Getting "cannot find symbol" error while using static methods

I have really simple code, I have deleted odd code.
So this my class, one of his method is static and I would like to use it later in Main class:
public class TradeInformationReader {
private static String tradeType = "FX_SPOT";
public static double tradePrice = -1;
private double price;
public static int setTradeInformation(String path_to_file) {
return 1;
}
}
And here how I trying to call this last method:
public class Main {
public static int main(String[] args) {
String path_to_file = "D:\\1.txt";
if (0 > TradeInformationReader.setTradeInformation(path_to_file)) {
return -1;
}
return 1;
}
}
I read many posts with a similar issue, but couldn't find a solution. Everything looks fine to me. IDE doesn't show any mistakes and I'm trying just to call static method setTradeInformation, why it does not recognize it (cannot find symbol method setTradeInformation)? Any ideas? I will really appreciate your help.
Your main is not a valid main, so I guess your IDE cannot find a launching class. This should be
public static void main(String[] args)
First you have to put TradeInformationReader class in a seperate file called : TradeInformationReader.java
as follows : `
public class TradeInformationReader {
private static String tradeType = "FX_SPOT";
public static double tradePrice = -1;
private double price;
public static int setTradeInformation(String path_to_file) {
//integer to identify whether the file is found or not 1 if found and 0 if not
int isFileFound = 1;
// the code required to get the file and modify the state of the of isFileFound variable
return isFileFound;
}
}
`
then the main class should have void return type and should be in a file that has the same name as the Main Class as follows:
public class firstApp {
public static void main(String[] args) {
String path_to_file = "D:\\1.txt";
if (0 > TradeInformationReader.setTradeInformation(path_to_file)) {
System.out.println("File not found");
}
}
}
`

Using enums in Java

Constants given in the following enum,
enum StringConstatns {
ONE {
#Override
public String toString() {
return "One";
}
},
TWO {
#Override
public String toString() {
return "Two";
}
}
}
public final class Main {
public static void main(String... args) {
System.out.println(StringConstatns.ONE + " : " + StringConstatns.TWO);
}
}
can be accessed just like StringConstatns.ONE and StringConstatns.TWO as shown in the main() method.
I have the following enum representing an int constant(s).
public enum IntegerConstants
{
MAX_PAGE_SIZE(50);
private final int value;
private IntegerConstants(int con) {
this.value = con;
}
public int getValue() {
return value;
}
}
This requires accessing the constant value like IntegerConstants.MAX_PAGE_SIZE.getValue().
Can this enum be modified somehow in a way that value can be accessed just like IntegerConstants.MAX_PAGE_SIZE as shown in the first case?
The answer is no, you cannot. You have to call:
IntegerConstants.MAX_PAGE_SIZE.getValue()
If you really want a shortcut, you could define a constant somewhere like this:
public class RealConstants {
final public static int MAX_PAGE_SIZE = 50;
}
public enum IntegerConstants
{
MAX_PAGE_SIZE(RealConstants.MAX_PAGE_SIZE);//reuse the constant
private final int value;
private IntegerConstants(int con) {
this.value = con;
}
public int getValue() {
return value;
}
}
This is not going to work because your first example does implicit calls to .toString() when you concatenate them with +, whereas there is no implicit conversion to int which is needed for your second example.
You could define them as static final fields, this does exactly what you are searching for:
public class IntegerConstants {
public static final int MAX_PAGE_SIZE = 50;
}

Retrieve a static variable using its name dynamically using reflection

How to retrieve a static variable using its name dynamically using Java reflection?
If I have class containing some variables:
public class myClass {
final public static string [][] cfg1= {{"01"},{"02"},{"81"},{"82"}};
final public static string [][]cfg2= {{"c01"},{"c02"},{"c81"},{"c82"}};
final public static string [][] cfg3= {{"d01"},{"d02"},{"d81"}{"d82"}};
final public static int cfg11 = 5;
final public static int cfg22 = 10;
final public static int cfg33 = 15;
}
And in another class I want variable name is input from user:
class test {
Scanner in = new Scanner(System.in);
String userInput = in.nextLine();
// get variable from class myClass that has the same name as userInput
System.out.println("variable name " + // correct variable from class)
}
Using reflection. Any help please?
You need to make use of java reflect. Here is a sample code. For example, I accessed 'cfg1' variable using java reflection, and then printed it into the console. Look into the main method carefully. I have handled no exceptions for simplification. The key line here is:
(String[][]) MyClass.class.getField("cfg1").get(MyClass.class);
__ ^typecast__ ^accessingFeild______________ ^accessFromClassDefinition
public class MyClass {
final public static String[][] cfg1 = { { "01" }, { "02" }, { "81" },
{ "82" } };
final public static String[][] cfg2 = { { "c01" }, { "c02" }, { "c81" },
{ "c82" } };
final public static String[][] cfg3 = { { "d01" }, { "d02" }, { "d81" },
{ "d82" } };
final public static int cfg11 = 5;
final public static int cfg22 = 10;
final public static int cfg33 = 15;
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException, NoSuchFieldException, SecurityException {
String[][] str = (String[][]) MyClass.class.getField("cfg1").get(
MyClass.class);
for (String[] strings : str) {
for (String string : strings) {
System.out.println(string);
}
}
}
}
If I well understood your needs, this could suit them:
// user input, hardcoded for the example
String fieldName = "cfg22";
MyClass blank = new MyClass();
Object value = null;
try {
value = MyClass.class.getDeclaredField(fieldName).get(blank);
} catch (IllegalArgumentException e) {
// if the specified object is not an instance of the class or
// interface declaring the underlying field (or a subclass or
// implementor thereof)
e.printStackTrace();
} catch (SecurityException e) {
// if a security manager, s, is present [and restricts the access to
// the field]
e.printStackTrace();
} catch (IllegalAccessException e) {
// if the underlying field is inaccessible
e.printStackTrace();
} catch (NoSuchFieldException e) {
// if a field with the specified name is not found
e.printStackTrace();
}
System.out.println(value);
Prints 10.
I merge the two above solutions and get:
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
public class MyClass
{
final public static String[][] cfg1 = {{"01"}, {"02"}, {"81"},
{"82"}};
final public static String[][] cfg2 = {{"c01"}, {"c02"}, {"c81"},
{"c82"}};
final public static String[][] cfg3 = {{"d01"}, {"d02"}, {"d81"},
{"d82"}};
final public static int cfg11 = 5;
final public static int cfg22 = 10;
final public static int cfg33 = 15;
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException, NoSuchFieldException, SecurityException
{
for (Field field : MyClass.class.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
System.out.println("Non-static field: " + field.getName());
}
else {
System.out.println("Static field: " + field.getName());
Object obj = MyClass.class.getField(field.getName()).get(MyClass.class);
if (obj instanceof String[][]) {
String[][] cad = (String[][]) obj;
for (String[] strings : cad) {
System.out.println("Values:: " + Arrays.toString(strings));
}
}
else {
System.out.println(" " + obj.toString());
}
}
}
}
}
You can try something like this :
for (Field field : myClass.class.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
System.out.println("Non-static field: " + field.getName());
}
else {
System.out.println("Static field: " + field.getName());
}
}
Use Field#get(Object obj) to get the value .
Note: Please follow Java naming conventions.
Just call Class.getField() or Class.getDeclaredField(), then call Field.getValue() on the result, providing null (or the class itself) as the parameter in the case of a static variable, or an instance of the class in the case of an instance variable.

error: no enclosing instance of type BPN is in scope {

class BPN {
public class BackpropagationNet extends NeuralNet
{
Vector neuronLayerVector;
NeuronLayer[] neuronLayerArray;
//...
public BackpropagationNet()
{
this.learningCycle = 0;
this.maxLearningCycles = -1;
//....
resetTime();
}
//some functions
void addNeuronLayer(int paramInt)
{//.... }
void connectLayers()
{//....}
}
abstract class NeuralNet
{
final int PATTERN_LENGTH = 100;
final int PATTERN_VALUE = 101;
final int PATTERNFILE_LENGTH = 102;
final int GENERAL_IO = 104;
//....
}
static BackpropagationNet bpn;
public static void main ( String[] args ) {
// some logic...
bpn = new BackpropagationNet();
//...
}
}
Well, this is short program which should demonstrate the problem.
When i try to compile i receive this error:
no enclosing instance of type BPN is in scope {(line 9)
remove static keyword from the class, top-level class cannot declared as static class.

Categories

Resources