private static final in detail please - static

What is the use if we use private static final to create an object of a class which is in another package..??
package pack1;
class C1{
...
}
class L1{
...
}
package pack2;
import pack1.C1;
import pack1.L1;
public class Main{
private static final C1 c1=new C1();
private static final L1 l1=new L1();
public static void main(String args[]){
...
}
}

The first result on Google!
http://geekwhorled.blogspot.com/2004/07/simple-java-questions-1-private-static.html

Related

The springAOP of pointcut using #annotation is not effective when applied to IbatisDAO

Annotation:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface IbatisAnno {}
Aspect:
#Component
#Aspect
public class IbatisAsepct {
//not works
#Pointcut("#annotation(xxx.IbatisAnno)")
public void m(){}
//works
#Pointcut("execution(* xxx.xxDAO.*(..))")
public void m2(){}
#Before("m()")
public void testM(){
System.out.println("Before Method...............");
}
#Before("m2()")
public void testM2(){
System.out.println("Before Method2...............");
}
}
Target class:
#EnableAspectJAutoProxy()
public class IbatisOfferFeedDAO extends SqlMapClientDaoSupport implements OfferFeedDAO{
#IbatisAnno
public void xxx(){
this.getSqlMapClientTemplate().insert();
}
}
Aspect does not take effect when using #Pointcut("#annotation(xxx.IbatisAnno)"), but it works when using #Pointcut("execution(* xxx.xxDAO.*(..))").

File Yaml to object using Yamlbeans library

I tried using yaml file named contact to write it into object. Unfortunately it didn't work...
package javaapplication22;
import com.esotericsoftware.yamlbeans.YamlException;
import com.esotericsoftware.yamlbeans.YamlReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class JavaApplication22 {
public class Contact {
public String name;
public int age;
}
public static void main(String[] args) throws FileNotFoundException, YamlException {
YamlReader reader = new YamlReader(new FileReader("contact.yml"));
Contact contact = reader.read(Contact.class);
System.out.println(contact.age);
}
}
I don't know why it doesn't work.Could somebody help me?
You can't reference JavaApplication22$Contact in a static-method.
In one word, in order to call
Contact contact = reader.read(Contact.class);
You have to make sure you can call the constructor there:
Contact test = new Contact();
In your code, you can't new an object of class Contact in main method.
There are two methods to work around:
1) change Contact to static
public static class Contact {
public String name;
public int age;
}
2) Don't define Contact as an inner class

Test class for public final static string

How to write a test class for a class containing public final static strings in salesforce?
I tried using system.assertequals
Doesnt seem to work properly.
#isTest
private class Test_TPET_Constants{
private static testMethod void test() {
//TPET_Constants inst= new TPET_Constants();
System.assertEquals(TPET_Constants.PICKLIST_COLLAB_SERVICE_SECURE_EMAIL,'Enterprise Secure Email');
System.assertEquals(TPET_Constants.DRAFT_STATUS, 'Draft');
System.assertEquals(TPET_Constants.ACTIVE_STATUS, 'Active');
System.assertEquals(TPET_Constants.INACTIVE_STATUS, 'Inactive');
System.assertEquals(TPET_Constants.SUBMITTED_STATUS, 'Submitted');
System.assertEquals(TPET_Constants.REJECTED_STATUS , 'Rejected');
System.assertEquals(TPET_Constants.PICKLIST_COLLAB_SERVICE , 'Collab Service');
System.assertEquals(TPET_Constants.PENDING_IMPLEMENTATION_STATUS ,'Pending Implementation');
}
}
In your class you need to markthe variable #TestVisible. Check here: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_testvisible.htm.
#TestVisible private static Integer recordNumber = 1;

testng how to dynamically set groups from Factory?

Before I setup a test class like the code below:
1. the Factory and test Dataprovider both used excel as the dataprovider.
2. In the Factory dataprovider table, it has a list of url
3. Each time, it will find one of the url in the factory dataprovider table, and run the test in each test methods..
public class Test {
WebDriver driver;
private String hostName;
private String url;
#Factory(dataProvider = "xxxx global variables", dataProviderClass = xxxx.class)
public GetVariables(String hostName, String url) {
this.hostName = hostName;
this.url = url;
}
#BeforeMethod
#Parameters("browser")
public void start(String browser) throws Exception {
driver = new FirefoxDriver();
driver.get(url);
Thread.sleep(1000);
}
#Test(priority = 10, dataProvider = "dataprovider Test A", dataProviderClass = xxx.class)
public void TestA(Variable1,
Variable2,Variable3) throws Exception {
some test here...
}
#Test(priority = 20, dataProvider = "dataprovider Test B", dataProviderClass = xxx.class)
public void TestB(Variable1,
Variable2,Variable3)
throws Exception {
some test here...
}
#AfterMethod
public void tearDown() {
driver.quit();
}
Now I want to dynamically assign different group for each test for different url. I am thinking add a variable 'flag' in the #Factory dataprovider:
#Factory(dataProvider = "xxxx global variables", dataProviderClass = xxxx.class)
public GetVariables(String hostName, String url, String flag) {
this.hostName = hostName;
this.url = url;
this.flag = flag;
}
That when flag.equals("A"), it will only run test cases in test groups={"A"}.
When flag.equals("B"), it will only run test cases in test groups ={"B"},
When flag.equals("A,B"), it will only run test cases in test groups ={"A","B"}
Is there any way I can do that?
Thank you!
TestNG groups provides "flexibility in how you partition your tests" but it isn't for conditional test sets. For that you simply use plain old Java.
You can use inheritance or composition (I recommend the latter, see Item 16: Favor composition over inheritance from Effective Java).
Either way the general idea is the same: use a Factory to create your test class instances dynamically creating the appropriate class type with the appropriate test annotations and/or methods that you want to run.
Examples:
Inheritance
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
public class DemoTest {
#Factory
public static Object[] createTests() {
return new Object[]{
new FlavorATest(),
new FlavorBTest(),
new FlavorABTest()
};
}
/**
* Base test class with code for both A-tests and B-tests.
*
* Note that none of these test methods are annotated as tests so that
* subclasses may pick which ones to annotate.
*/
public static abstract class BaseTest {
protected void testA() {
// test something specific to flavor A
}
protected void testB() {
// test something specific to flavor B
}
}
// extend base but only annotate A-tests
public static class FlavorATest extends BaseTest {
#Test
#Override
public void testA() {
super.testA();
}
}
// extend base but only annotate B-tests
public static class FlavorBTest extends BaseTest {
#Test
#Override
public void testB() {
super.testB();
}
}
// extend base and annotate both A-tests and B-tests
public static class FlavorABTest extends BaseTest {
#Test
#Override
public void testA() {
super.testA();
}
#Test
#Override
public void testB() {
super.testB();
}
}
}
Composition
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
public class DemoTest {
#Factory
public static Object[] createTests() {
return new Object[]{
new FlavorATest(),
new FlavorBTest(),
new FlavorABTest()
};
}
private static void testA() {
// test something specific to flavor A
}
private static void testB() {
// test something specific to flavor B
}
// only create A-test methods and delegate to shared code above
public static class FlavorATest {
#Test
public void testA() {
DemoTest.testA();
}
}
// only create B-test methods and delegate to shared code above
public static class FlavorBTest {
#Test
public void testB() {
DemoTest.testB();
}
}
// create A-test and B-test methods and delegate to shared code above
public static class FlavorABTest {
#Test
public void testA() {
DemoTest.testA();
}
#Test
public void testB() {
DemoTest.testB();
}
}
}
Your factory methods won't be as simple as you'll need to use your "flag" from your test data to switch off of and create instances of the appropriate test classes.

Java: how to "restart" a static class?

I have a static class (Foo) and a main class (Main)
See Main.java:
public class Main {
public static void main(String[] args) {
System.out.println(Foo.i); // 0
Foo.i++;
System.out.println(Foo.i); // 1
// restart Foo here
System.out.println(Foo.i); // 1 again...I need 0
}
}
See Foo.java:
public class Foo {
public static int i = 0;
}
Is there any way to restart or reset a static class?
Note: I need this because I'm testing a static class with jUnit and I need to clean parameters before second test.
EDIT
ALMOST SOLUTION:
Using StanMax answer, I can to this:
Main.java
public class Main {
public static void main(String[] args) throws Exception {
test();
test();
}
public static void test() throws Exception {
System.out.println("\ntest()");
MyClassLoader myClassLoader = new MyClassLoader();
Class<?> fooClass = myClassLoader.loadClass(Foo.class.getCanonicalName());
Object foo = fooClass.newInstance();
System.out.println("Checking classloader: " + foo.getClass().getClassLoader());
System.out.println("GC called!");
System.gc();
}
}
MyClassLoader.java
public class MyClassLoader {
private URLClassLoader urlClassLoader;
public MyClassLoader() {
try {
URL url = new File(System.getProperty("user.dir") + "/bin/").toURL();
URL[] urlArray = {url};
urlClassLoader = new URLClassLoader(urlArray, null);
} catch (Exception e) {
}
}
public Class<?> loadClass(String name) {
try {
return (Class<?>) urlClassLoader.loadClass(name);
} catch (Exception e) {
}
return null;
}
#Override
protected void finalize() throws Throwable {
System.out.println("MyClassLoader - End.");
}
}
Foo.java
public class Foo {
public static int i = 0;
static {
System.out.println("Foo - BEGIN ---------------------------------");
}
public void finalize() throws Throwable {
System.out.println("Foo - End.");
}
}
OUTPUT
test()
Foo - BEGIN ---------------------------------
Checking classloader: java.net.URLClassLoader#ec160c9
GC called!
MyClassLoader - End.
Foo - End.
test()
Foo - BEGIN ---------------------------------
Checking classloader: java.net.URLClassLoader#ec3fb9b
GC called!
MyClassLoader - End.
Foo - End.
PROBLEM: if I do the cast bellow:
Foo foo = (Foo) fooClass.newInstance();
I get error:
java.lang.ClassCastException
Only if you can unload class, get it re-loaded, as class static code gets executed when class is loaded.
But you can just directly modify the value:
Foo.i = 0;
(or create equivalent method for doing it, esp. if static member is not public)
Create a static method that sets the class variables to their initial values, then call it when you need it.
Avoid static.
It is well known that static is not testable and should thus be avoided. For example, avoiding static is one of the key motivations behind dependency injection. If you need one instance only at runtime, use the singleton pattern instead. And create a new instance for each test run.
You can try this.
Main MainObject = new Main;
MainObject.main(args);
It will restart the class again and again until you stop the class.

Resources