How to test the "key" and "value" of config.properties file? - java

I have a class ReadPropertyFile which has a method getPropertyFor() of return type string(which is the value corresponding to key passed as parameter).I need help to test the getPropertyFor() method for both value and the key using Junit.
public class ReadPropertyFile {
private Properties properties;
public ReadPropertyFile(String propertyFileName) {
properties= new Properties();
try {
properties.load(new FileReader(propertyFileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getPropertyFor(String key) {
String value = properties.getProperty(key);
if(value == null) {
try {
throw new Exception(key + " not found!");
} catch (Exception e) {
e.printStackTrace();
}
}
return value;
}
}
I have written the following test case to test the value for the key provided.
How do I test the "key" whether it is contained in the testconfig.properties file?
The contents of the testConfig.properties are as follows:
FILE_NAME=D:/Refreshed_data_daily/all_hue_posts_in_excel.xlsx

If the key is not defined in the file,
the getProperties method returns null.
If the key exists but has no value,
the getProperties method returns an empty string.
The way you catch and throw exception in the file doesn't make much sense.
You could simplify your method as:
public String getPropertyFor(String key) {
return properties.getProperty(key);
}
Given this content in testConfig.properties:
FILE_NAME = D:/Refreshed_data_daily/all_hue_posts_in_excel.xlsx
empty.test =
You could unit test the different cases like this:
private String getProperty(String key) {
new ReadPropertyFile("testConfig.properties").getPropertyFor(key)
}
#Test
public void testMissingKey() {
assertNull(getProperty("nonexistent"));
}
#Test
public void testEmptyKey() {
assertEquals("", getProperty("empty.prop"));
}
#Test
public void testValue() {
assertEquals("D:/Refreshed_data_daily/all_hue_posts_in_excel.xlsx", getProperty("FILE_NAME"));
}

Related

Increment number every time program runs

I want to increment the count every time my program runs. I tried running below code but it keeps on printing 1 every time i run the program. Also anything special i need to do to increase the date.
public class CounterTest {
int count = 0;
public static void main(String[] args) {
CounterTest test1 = new CounterTest();
test1.doMethod();
}
public void doMethod() {
count++;
System.out.println(count);
}
}
You could simply create a properties file for your application to keep track of such things and application configuration details. This of course would be a simple text file containing property names (keys) and their respective values.
Two small methods can get you going:
The setProperty() Method:
With is method you can create a properties file and apply whatever property names and values you like. If the file doesn't already exist then it is automatically created at the file path specified:
public static boolean setProperty(String propertiesFilePath,
String propertyName, String value) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
}
try (java.io.FileOutputStream outputStream = new java.io.FileOutputStream(propertiesFilePath)) {
prop.setProperty(propertyName, value);
prop.store(outputStream, null);
outputStream.close();
return true;
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
catch (java.io.IOException ex) {
System.err.println(ex);
}
return false;
}
If you don't already contain a specific properties file then it would be a good idea to call the above method as soon as the application starts (perhaps after initialization) so that you have default values to play with if desired, for example:
if (!new File("config.properties").exists()) {
setProperty("config.properties", "ApplicationRunCount", "0");
}
The above code checks to see if the properties file named config.properties already exists (you should always use the .properties file name extension). If it doesn't then it is created and the property name (Key) is applied to it along with the supplied value for that property. Above we are creating the ApplicationRunCount property which is basically for your specific needs. When you look into the config.properties file created you will see:
#Mon Sep 28 19:07:08 PDT 2020
ApplicationRunCount=0
The getProperty() Method:
This method can retrieve a value from a specific property name (key). Whenever you need the value from a particular property contained within your properties file then this method can be used:
public static String getProperty(String propertiesFilePath, String key) {
try (java.io.InputStream ips = new java.io.FileInputStream(propertiesFilePath)) {
java.util.Properties prop = new java.util.Properties();
prop.load(ips);
return prop.getProperty(key);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return null;
}
Your Task:
What is confusing here is you say you want to keep track of the number of times your Program is run yet you increment your counter variable named count within a method named doMethod(). This would work if you can guarantee that this method will only run once during the entire time your application runs. If this will indeed be the case then you're okay. If it isn't then you would possibly get a count total that doesn't truly represent the actual number of times your application was started.
In any case, with the scheme you're currently using, you could do this:
public class CounterTest {
// Class Constructor
public CounterTest() {
/* If the config.properties file does not exist
then create it and apply the ApplicationRunCount
property with the value of 0. */
if (!new java.io.File("config.properties").exists()) {
setProperty("config.properties", "ApplicationRunCount", "0");
}
}
public static void main(String[] args) {
new CounterTest().doMethod(args);
}
private void doMethod(String[] args) {
int count = Integer.valueOf(getProperty("config.properties",
"ApplicationRunCount"));
count++;
setProperty("config.properties", "ApplicationRunCount",
String.valueOf(count));
System.out.println(count);
}
public static String getProperty(String propertiesFilePath, String key) {
try (java.io.InputStream ips = new
java.io.FileInputStream(propertiesFilePath)) {
java.util.Properties prop = new java.util.Properties();
prop.load(ips);
return prop.getProperty(key);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return null;
}
public static boolean setProperty(String propertiesFilePath,
String propertyName, String value) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
}
try (java.io.FileOutputStream outputStream = new java.io.FileOutputStream(propertiesFilePath)) {
prop.setProperty(propertyName, value);
prop.store(outputStream, null);
return true;
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
catch (java.io.IOException ex) {
System.err.println(ex);
}
return false;
}
}
Whenever you start your application you will see the run count within the Console Window. Other useful methods might be removeProperty() and renameProperty(). Here they are:
/**
* Removes (deletes) the supplied property name from the supplied property
* file.<br>
*
* #param propertiesFilePath (String) The full path and file name of the
* properties file you want to remove a property name from.<br>
*
* #param propertyName (String) The property name you want to remove from
* the properties file.<br>
*
* #return (Boolean) Returns true if successful and false if not.
*/
public static boolean removeProperty(String propertiesFilePath,
String propertyName) {
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
prop.remove(propertyName);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false; }
}
try (java.io.FileOutputStream out = new java.io.FileOutputStream(propertiesFilePath)) {
prop.store(out, null);
return true;
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); }
catch (java.io.IOException ex) { System.err.println(ex); }
return false;
}
/**
* Renames the supplied property name within the supplied property file.<br>
*
* #param propertiesFilePath (String) The full path and file name of the
* properties file you want to rename a property in.<br>
*
* #param oldPropertyName (String) The current name of the property you want
* to rename.<br>
*
* #param newPropertyName (String) The new property name you want to use.<br>
*
* #return (Boolean) Returns true if successful and false if not.
*/
public static boolean renameProperty(String propertiesFilePath, String oldPropertyName,
String newPropertyName) {
String propertyValue = getProperty(propertiesFilePath, oldPropertyName);
if (propertyValue == null) { return false; }
java.util.Properties prop = new java.util.Properties();
if (new java.io.File(propertiesFilePath).exists()) {
try (java.io.FileInputStream in = new java.io.FileInputStream(propertiesFilePath)) {
prop.load(in);
prop.remove(oldPropertyName);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false ;}
}
try (java.io.FileOutputStream out = new java.io.FileOutputStream(propertiesFilePath)) {
prop.store(out, null);
}
catch (java.io.FileNotFoundException ex) { System.err.println(ex); return false; }
catch (java.io.IOException ex) { System.err.println(ex); return false; }
return setProperty(propertiesFilePath, newPropertyName, propertyValue);
}
Try this.
public class CounterTest {
static final Path path = Path.of("counter.txt");
int count;
CounterTest() throws IOException {
try {
count = Integer.valueOf(Files.readString(path));
} catch (NoSuchFileException | NumberFormatException e) {
count = 0;
}
}
public void doMethod() throws IOException {
++count;
System.out.println(count);
Files.writeString(path, "" + count);
}
public static void main(String[] args) throws IOException {
CounterTest c = new CounterTest();
c.doMethod();
}
}
You can't the only way is to use a Database or simpler use a txt file to save the number and every time you run your app reads the txt file and gets the number.
Here is How to do it:
This is the Main class:
package main;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String path = "C:\\Example.txt";
int number = 0;
try {
ReadFile file = new ReadFile(path);
String[] aryLines = file.OpenFile();
try {
number = Integer.parseInt(aryLines[0]);
} catch (Exception e) {
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println(number);
number++;
File txtfile = new File(path);
if (txtfile.exists()) {
txtfile.delete();
try {
txtfile.createNewFile();
WriteFile data = new WriteFile(path, true);
data.writeToFile(number + "");
} catch (IOException ex) {
}
} else {
try {
System.out.println("no yei");
txtfile.createNewFile();
WriteFile data = new WriteFile(path, true);
data.writeToFile(number + "");
} catch (IOException ex) {
}
}
}
}
the class that writes anything you need:
package main;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class WriteFile {
public String path;
public boolean append_to_file = false;
public WriteFile(String file_path) {
path = file_path;
}
public WriteFile(String file_path, boolean append_value) {
path = file_path;
append_to_file = append_value;
}
public void writeToFile(String textline) throws IOException {
FileWriter write = new FileWriter(path, append_to_file);
PrintWriter print_line = new PrintWriter(write);
print_line.printf("%s" + "%n", textline);
print_line.close();
}
}
And this one is the one that gets the text on the file:
package main;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class ReadFile {
private static String path;
public ReadFile(String file_path){
path = file_path;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
for (int j = 0; j < numberOfLines; j++) {
textData[j] = textReader.readLine();
}
textReader.close();
return textData;
}
static int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
String aLine;
int numberOfLines = 0;
while((aLine = bf.readLine()) != null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}
}

Storing null as value of Entity Property?

Since Entity store is throwing out when storing null value, I managed to get a "hack" to save a null value into it. However I am not sure if my approach is futile.
Here's a snippet:
entityStore.executeInTransaction(new StoreTransactionalExecutable() {
#Override
public void execute(#NotNull final StoreTransaction txn) {
try {
entityStore.registerCustomPropertyType(txn, UndefinedIterable.class, UndefinedBinding.BINDING);
} catch (Exception e) {
}
final Entity entity = txn.newEntity(storeName);
Iterator<String> it = comparableMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
Comparable value = comparableMap.get(key);
if(value == null) {
entity.setProperty(key, new UndefinedIterable());
} else {
entity.setProperty(key, value);
}
}
First question here is, is it safe to registerCustomPropertyType over and over again, since this method will be called each time the server gets a POST request.
Next is the UndefinedIterable even needed here?
Here's the complete code
UndefinedIterable.java
public class UndefinedIterable implements Serializable, ByteIterable {
private byte[] bytes;
public UndefinedIterable() {
bytes = "null".getBytes();
}
#Override
public ByteIterator iterator() {
return new ArrayByteIterable(bytes).iterator();
}
#Override
public byte[] getBytesUnsafe() {
return bytes;
}
#Override
public int getLength() {
return bytes.length;
}
#NotNull
#Override
public ByteIterable subIterable(int offset, int length) {
return null;
}
#Override
public int compareTo(#NotNull ByteIterable o) {
return 0;
}
}
UndefinedBinding.java
public class UndefinedBinding extends ComparableBinding {
public static final UndefinedBinding BINDING = new UndefinedBinding();
#Override
public Comparable readObject(#NotNull ByteArrayInputStream stream) {
try {
byte[] serialized = ByteStreams.toByteArray(stream);
Comparable deserialized = deserialize(serialized, Comparable.class);
return deserialized;
} catch (Exception e) {
}
return null;
}
#Override
public void writeObject(#NotNull LightOutputStream output, #NotNull Comparable object) {
byte[] serialized = serialize(object);
output.write(serialized);
}
public static byte[] serialize(Object obj) {
try {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos)) {
out.writeObject(obj);
return bos.toByteArray();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static <T> T deserialize(byte[] data, Class<T> clazz) {
try {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return (T) is.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
I am afraid that my approach might be a bit overkill for the simple job of saving a null value?
It's safe to registerCustomPropertyType several times, though it is intended to be called usually once on an init stage.
If I really need to distinguish lack of property value and property having null value, then I'd try to define non-null values replacing null. For String, it can be hex representation of an UUID. For Integer, Integer.MIN_VALUE or Integer.MAX_VALUE, etc. Don't use values of mixed types for a single property, otherwise search by property value or range search won't work.

Sorting keyset of java.util.property

for some reason, I'm in a situation where I need to use a property file like:
1=1
2=2
3=3
4=4
5=5
6=6
7=7
12=12
13=13
14=14
15=15
16=16
17=17
23=23
24=24
25=25
26=26
27=27
34=34
35=35
36=36
37=37
45=45
46=46
47=47
56=56
57=57
67=67
123=123
124=124
125=125
126=126
.................
24567=24567
34567=34567
123456=123456
123457=123457
123467=123467
123567=123567
124567=124567
134567=134567
234567=234567
1234567=1234567
And I have utility handler class to sort the keys
public class PropertyHandler {
private static PropertyHandler instance;
private Properties properties;
private PropertyHandler() {
InputStream fos = null;
try {
fos = PropertyHandler.class.getClassLoader().getResourceAsStream("dow-pattern.properties");
properties = new Properties() {
#Override
public Set<Object> keySet() {
return Collections.unmodifiableSet(new TreeSet<Object>(super.keySet()));
}
#Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(new TreeSet<Object>(super.keySet()));
}
};
properties.load(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static PropertyHandler getInstance() {
if (instance == null) {
instance = new PropertyHandler();
}
return instance;
}
private Properties getProperties() {
return properties;
}
public static String getStringProperty(String propertyName) {
return PropertyHandler.getInstance().getProperties().getProperty(propertyName);
}
public static int getIntProperty(String propertyName) {
return Integer.parseInt(PropertyHandler.getInstance().getProperties().getProperty(propertyName));
}
public static Set<Object> getAllKeys() {
return PropertyHandler.getInstance().getProperties().keySet();
}
}
But when I print the keys, by calling "getAllKeys()" the order of keys as not expected. It is printed in a random fashion.
1
12
123
1234
12345
123456
1234567
123457
12346
123467
12347
1235
12356
123567
12357
1236
........
Any pointers to solve this issue would be helpful.
That's not random, that's sorted alphabetically. You need to sort the values numerically. The easiest way would be converting the Strings to Integers before adding them to the TreeSet.

How to get the object reference of a field of an object using reflection?

Note: Every time I go to type up this question, I think I see something, but it never pans out, so for the third or fourth time.
Synopsis: I am trying to serialize an object that inherits from the base Response class using the Response class, of which the subclass may have non-primitive field types.
The code is as such (warning: large and not elegant), ordered from the specific class (SpecificResponse), as extended from a common class (CommonResponse), which is a concrete implementation of the abstract class (Response), driven by a test program (Program).
// SpecificResponse.java
package com.jdgj.thinking;
public final class SpecificResponse extends CommonResponse {
public String hell;
public int trike;
public short tail;
public SpecificResponse() {
super();
}
}
SpecifcResponse extends CommonResponse:
// CommonResponse.java
package com.jdgj.thinking;
public class CommonResponse extends Response {
public int thing2;
public Value value;
#Override
protected void initialize() {
System.out.println("hello!");
value = new Value();
}
}
For testing purposes, I just made a simple Value object:
// Value.java
package com.jdgj.thinking;
public class Value {
public int five;
}
And, that which does a lot of work, and also the foundation for CommonResponse, the Response class:
// Response.java
package com.jdgj.thinking;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
public abstract class Response {
public static Class<?> fromClassSignature(List<String> signature) throws IllegalArgumentException, IllegalStateException, ClassNotFoundException {
if (signature == null || signature.size() == 0) {
throw new IllegalArgumentException("Null or empty Response class signature.");
}
String lastClassName = null;
for (String line : signature) {
if (line.startsWith("class:")) {
lastClassName = line.split(":")[1];
}
}
if (lastClassName == null) {
throw new IllegalStateException("Could not find the Response class name.");
}
Class<?> c = Class.forName(lastClassName);
lastClassName = null;
Class<?> sc = c.getSuperclass();
while (sc != null && !sc.equals(Response.class)) {
sc = sc.getSuperclass();
}
if (sc != null) {
sc = null;
return c;
} else {
return null;
}
}
protected abstract void initialize();
private String getFieldSignature(Field field) {
return "field:" + field.getName() + "|" + field.getType().getCanonicalName();
}
private List<String> serializeObject(Class<?> c, Object o) {
List<String> serialization = new ArrayList<String>(0);
serialization.add("class:" + c.getName());
for (Field f : c.getDeclaredFields()) {
if (!f.isSynthetic() && Modifier.isPublic(f.getModifiers())) {
StringBuilder sb = new StringBuilder(getFieldSignature(f));
Class<?> t = f.getType();
Object value = null;
try {
value = f.get(o);
System.out.println(f.getName() + "=" + value);
if (t.isPrimitive() || t.equals(String.class)) {
sb.append("`" + value.toString() + "");
}
} catch (NullPointerException e) {
if (t.isPrimitive() || t.equals(String.class)) {
sb.append("`");
} else {
System.out.println("UNEXPECTED NULL POINTER EXCEPTION");
}
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
serialization.add(sb.toString());
if (value != null) {
if (!(t.isPrimitive() || t.equals(String.class))) {
serialization.addAll(serializeObject(t, value));
}
}
}
sb = null;
t = null;
}
}
return serialization;
}
private List<String> describeClass(Class<?> c) {
List<String> description = new ArrayList<String>(0);
description.add("class:" + c.getName());
for (Field f : c.getDeclaredFields()) {
if (!f.isSynthetic() && Modifier.isPublic(f.getModifiers())) {
description.add(getFieldSignature(f));
Class<?> t = f.getType();
if (!(t.isPrimitive() || t.equals(String.class))) {
description.addAll(describeClass(t));
}
t = null;
}
}
return description;
}
public final List<String> getSerializedObject() {
Class<?> c = getClass();
List<String> object = new ArrayList<String>(0);
while (c != null && !c.equals(Response.class)) {
object.addAll(0, serializeObject(c, this));
c = c.getSuperclass();
}
c = null;
return object;
}
public final List<String> getClassSignature() {
Class<?> c = getClass();
List<String> signature = new ArrayList<String>(0);
while (c != null && !c.equals(Response.class)) {
signature.addAll(0, describeClass(c));
c = c.getSuperclass();
}
c = null;
return signature;
}
}
These classes are driven by a 'dev-test' program for now:
// Program.java
import com.jdgj.thinking.Response;
import com.jdgj.thinking.SpecificResponse;
public class Program {
private static void printClassSignature(Response response) {
for (String line : response.getClassSignature()) {
System.out.println(line);
}
}
private static void printSerializedObject(Response response) {
for (String line : response.getSerializedObject()) {
System.out.println(line);
}
}
public static void main(String[] args) {
String CN_SPECRSP = "com.jdgj.thinking.SpecificResponse";
Class<?> response = null;
try {
response = Response.fromClassSignature(new SpecificResponse().getClassSignature());
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
if (response != null) {
System.out.println("Expected: " + CN_SPECRSP + "; Actually: " + response.getCanonicalName());
Response rsp = null;
try {
rsp = (Response)response.newInstance();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (rsp != null) {
//printClassSignature(rsp);
printSerializedObject(rsp);
rsp = null;
}
}
response = null;
}
}
}
}
Here's the output:
Expected: com.jdgj.thinking.SpecificResponse; Actually: com.jdgj.thinking.SpecificResponse
hell=null
trike=0
tail=0
thing2=0
value=null
class:com.jdgj.thinking.CommonResponse
field:thing2|int`0
field:value|com.jdgj.thinking.Value
class:com.jdgj.thinking.SpecificResponse
field:hell|java.lang.String`
field:trike|int`0
field:tail|short`0
Why does value report null?
In both not having and having a constructor defined in CommonResponse to initialize the Value instance, it's still shown as null. If I uncomment the Program.getClassSignature method, the code delves into the Value object to get the five field:
Expected: com.jdgj.thinking.SpecificResponse; Actually: com.jdgj.thinking.SpecificResponse
class:com.jdgj.thinking.CommonResponse
field:thing2|int
field:value|com.jdgj.thinking.Value
class:com.jdgj.thinking.Value
field:five|int
class:com.jdgj.thinking.SpecificResponse
field:hell|java.lang.String
field:trike|int
field:tail|short
hell=null
trike=0
tail=0
thing2=0
value=null
class:com.jdgj.thinking.CommonResponse
field:thing2|int`0
field:value|com.jdgj.thinking.Value
class:com.jdgj.thinking.SpecificResponse
field:hell|java.lang.String`
field:trike|int`0
field:tail|short`0
I feel as if I've exhausted my Google-fu, and I feel like I'm missing something just.. blatantly obvious, but I cannot think of the reason, or the right query to ask Google. Everyone keeps providing ways to get primitive fields, but that is not what I am seeking. I therefore submit to the guidance of SO.
As Holger said you never initialize that field. You have a initialize() method to do it, but never invoke it.
Of course if you call getClassSignature() you get info about your field, actually it's there; you got a field named value of type com.jdgj.thinking.Value in your class, but it never has been instantiated, so that field value is null.

Is needed Return value or not?, Working with try, catch and Finally: Java

I have this code:
private String Style(String Arg, Vector VctrClass) throws Exception {
if (Verify that Arg is contained into VctrClass)) {
return "Something";
} else {
throw new Exception("Error The argument required \""+Arg+"\" doesn't exist<br>");
}
}
Here my problem, I had this method:
public String GetStylString(String Arg) {
try {
return this.Style(Arg,OneVector);
}
catch(Exception e) {
System.out.println(e.toString());
}
finally {
return "";
}
}
But' I have this message:
Void methods cannot return a value
Then I changed my method to:
public String GetStylString(String Arg) {
try {
return this.Style(Arg,OneVector);
}
catch(Exception e) {
System.out.println(e.toString());
}
}
I have this message:
This method must return a result of type String
Add the return after the println, not in the finally:
public String GetStylString(String Arg) {
try {
return this.Style(Arg,OneVector);
}
catch(Exception e) {
System.out.println(e.toString());
return "";
}
}
Add the return after the catch instead of in the finally:
public String GetStylString(String Arg) {
try {
return this.Style(Arg,OneVector);
}
catch(Exception e) {
System.out.println(e.toString());
}
return "";
}

Categories

Resources