I want to instantiate a URL as a private field in a class, but I can't catch the MalformedURLException. I've tried using a static initialization block, but that doesn't work either. How do I solve this?
public class MyClass{
private final static URL DEFAULT_URL = new URL("http://www.yadayada.com?wsdl")
...
}
You will need to throw something in the case of an exception. An Error should do the job.
public class MyClass{
private static final URL DEFAULT_URL;
static {
try {
DEFAULT_URL = new URL("http://www.yadayada.com?wsdl")
} catch (java.net.MalformedURLException exc) {
throw new Error(exc);
}
}
...
}
In case an exception is thrown (it shouldn't be) the class will fail to initialse.
A simple workaround is to create a static method:
private final static URL DEFAULT_URL = getDefaultUrl();
private static URL getDefaultUrl() {
try {
return new URL("http://www.yadayada.com?wsdl");
} catch (Exception e) {
//what do you want to do here?
return null; //that is an option
throw new AssertionError("Invalid URL"); //that is another one
}
}
You can do it in the static block
public class MyClass {
private final static URL DEFAULT_URL;
static {
try {
DEFAULT_URL = new URL("http://www.yadayada.com?wsdl");
} catch (MalformedURLException e) {
}
}
Using static block initializer - you may catch exception inside the block.
However, I would not recommend to store it as final class field as URI. Place it as String constant and initialize in constructor or special init() intance method
Try below. you cannot use final keyword for below:
private static URL DEFAULT_URL = null;
static{
try {
DEFAULT_URL = new URL("http://www.yadayada.com?wsdl");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Related
How could I wrote a ThrowingSupplier with an unchecked method that could replace this part of code? I have really no idea how to start with it should it be an interface or rather a class.
try {
// get connection with the database
connection = dataSource.getConnection();
} catch (Exception e) {
throw new UndeclaredThrowableException(e);
}
What I would like to get is something like
Connection connection = ThrowingSupplier.unchecked(dataSource::getConnection).get();
Any ideas how should it looks like? I am not sure if it should be an interface or a class I tried to wrote that, but then I could not create a static method unchecked and I would not to create new instance of that.
If I understand correctly, this is what you want:
public class ThrowingSupplier {
public static <T> Supplier<T> unchecked(Callable<T> callable) {
return () -> {
try {
return callable.call();
}
catch (Exception e) {
throw new UndeclaredThrowableException(e);
}
};
}
// example usage:
public static void main(String[] args) {
DataSource dataSource = null;
Connection connection = ThrowingSupplier.unchecked(dataSource::getConnection).get();
}
}
I've a class with few constants declared, initialized and I also have a private constructor.
For some reasons I'm writing Junits to achieve the code coverage.
Here I have used constructor.setaccessible(true) and I have initialized the class.
In the assert statement I'm expecting the length of the constructor to be 1.
I've achieved 100% code coverage for this class. But I'm quite not sure how. Can anyone please throw some light on this?
public class CommonConstants {
public static final String ABC= "ABC";
public static final String XYZ= "XYZ";
private CommonConstants() {}
}
#Test
public void stringTest() {
final Constructor<?>[] constructors = CommonConstants.class.getDeclaredConstructors();
constructors[0].setAccessible(true);
try {
CommonConstants cc = (CommonConstants) constructors[0].newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
Assert.assertEquals(1, constructors.length);
}
I try to load properties file as below,
public class A_Main {
private static FileReader reader = new FileReader("D:\\Selenium_Workspace\\SeleniumTEST\\lists.properties");
private static Properties properties = new Properties();
private static properties.load(reader);
public static String UserName = properties.getProperty("lists.user");
public static String Passwd = properties.getProperty("lists.password");
......
......
......
public static void main(String[] args) throws IOException {
Configuration_Report conf = new Configuration_Report();
try {
conf.conf_report(UserName, Passwd);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
......
......
......
However, in eclipse it marked an error under below code,
private static properties.load(reader);
I try to change everything to public static also, however it seem the properties file cannot be load as reader seem not recognize.
As shared by Elliott above, you need to call the load function either from the static block. If you call it from the static block then you will have to take care that you initialize username and password (and any other dependencies) as well in the static block. Or the other option would be to initialize them at the starting of the main function:
Static Block:
public class A_Main {
private static Properties properties = new Properties();
public static String UserName = null;
public static String Passwd = null;
static{
try (FileReader reader = new FileReader("D:\\Selenium_Workspace\\SeleniumTEST\\lists.properties"))
{
properties.load(reader);
UserName = properties.getProperty("lists.user");
Passwd = properties.getProperty("lists.password");
} catch (IOException e) {
e.printStackTrace();
}
}
......
......
......
public static void main(String[] args) throws IOException {
Configuration_Report conf = new Configuration_Report();
try {
conf.conf_report(UserName, Passwd);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
......
......
......
Inside Main Function:
public class A_Main {
private static Properties properties = new Properties();
public static String UserName = null;
public static String Passwd = null;
......
......
......
public static void main(String[] args) throws IOException {
try (FileReader reader = new FileReader("D:\\Selenium_Workspace\\SeleniumTEST\\lists.properties"))
{
properties.load(reader);
UserName = properties.getProperty("lists.user");
Passwd = properties.getProperty("lists.password");
Configuration_Report conf = new Configuration_Report();
conf.conf_report(UserName, Passwd);
} catch (IOException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
......
......
......
That is not valid syntax for invoking a function on a class member. You could use a static initialization block. And that FileReader constructor can also throw an Exception. You could move that initialization into the same block. Like,
private static FileReader reader;
private static Properties properties = new Properties();
static {
try {
reader = new FileReader("D:\\Selenium_Workspace\\SeleniumTEST\\lists.properties");
properties.load(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
Hi Below is my code which will use as Connection Factory class. But i am getting java.lang.ExceptionInInitializerError. Please advice how to fix? I assume this is the trap because of static block, but not aware what exactly is this.
package j2ee.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class ConnFactory
{
public static Properties prop;
static
{
prop=new Properties();
try {
prop.load(ConnFactory.class.getClassLoader().getResourceAsStream("DBConfig.properties"));
} catch (Exception e) {
e.printStackTrace();
}
}
private static ConnFactory instance = new ConnFactory();
public static final String URL = prop.getProperty("DEVURL");
public static final String USER = prop.getProperty("DEVUSER");
public static final String PASSWORD = prop.getProperty("DEVPASSWORD");
public static final String DRIVER_CLASS = prop.getProperty("DEVDRIVER_CLASS");
private ConnFactory() {
try {
Class.forName(DRIVER_CLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private Connection createConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (Exception e) {
System.out.println("ERROR: Unable to Connect to Database.");
}
return connection;
}
public static Connection getConnection() {
return instance.createConnection();
}
public static void main(String a[])
{
Connection test=ConnFactory.getConnection();
System.out.println("Done");
}
}
Error is :
Caused by: java.lang.NullPointerException
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:188)
at j2ee.dao.ConnFactory.<init>(ConnFactory.java:28)
at j2ee.dao.ConnFactory.<clinit>(ConnFactory.java:20)
private static ConnFactory instance = new ConnFactory(); // DRIVER_CLASS is null at this point
...
public static final String DRIVER_CLASS = ...;
You create an instance of ConnFactory before DRIVER_CLASS is initialized, therefore DRIVER_CLASS is null in the constructor of ConnFactory.
You need to reverse the order of these static field declarations:
public static final String DRIVER_CLASS = ...;
...
private static ConnFactory instance = new ConnFactory()
Actually, in my opinion it would be better to get rid of these static fields at all. Just make them non-static and initialize them in constructor.
You can also pass an instance of Properties into constuctor to decouple connection creation from storage of connection properties. If you do so, you will be able to use different sets of properties in different cases (for example, for test and production environments).
The class partially shown below contains a main method. When I run the code, I see a NullPointerException (NPE) and then an error message - "Could not find the main class, program will exit". My understanding is that if I get NPE, it means that the code is running, ie the JRE found a main method to begin execution, so why do I get the error message?
This is the console output
java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at com.MyWorldDemo.getValue(MyWorldDemo.java:57)
at com.MyWorldDemo.<clinit>(MyWorldDemo.java:23)
Exception in thread "main"
In a nutshell:
username is stored in a properties file.
properties file is like this username=superman....etc
here is some code example
class MyClass {
private final static String username = getData("username"); // ERROR HERE
private static Properties prop;
// more variables
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
// this method will assign a value to my final variable username.
public static String getData(String props) {
String property = prop.getProperty(props);// ERROR HERE !!!
return property;
}
}
Initializing of static variables depends on its position in code (variables are initialized from top to bottom). In your code
private final static String username = getData("username"); // ERROR HERE
private static Properties prop;
// more variables
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
prop object will be initialized after username in static block, but since to initialize username prop is necessary and its not initialized yet you get NPE. Maybe change your code to something like:
private static Properties prop = new Properties();
private final static String username = getData("username");
static {
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch (IOException ex) {
ex.printStackTrace();
}
}
You have a static initialization at line 23 of MyWorldDemo that is calling the method getValue, which is then causing a NPE at line 57, therefore the class cannot be instantiated, therefore the main method cannot be called. It probably looks something like:
class MyWorldDemo {
private static String foo = getValue("username");
private static Properties prop;
// This happens too late, as getValue is called first
static {
prop = new Properties();
try {
FileInputStream fis = new FileInputStream("MyDB.properties");
prop.load(fis);
} catch(IOException ex) {
ex.printStackTrace();
}
}
// This will happen before static initialization of prop
private static String getValue(String propertyValue) {
// prop is null
return prop.getProperty(propertyValue);
}
public static void main(String args[]) {
System.out.println("Hello!"); // Never gets here
}
}