Categories
discuss

Is it possible to create an instance of inner class using Java Reflection?

Sample of code:

public class Foo
{
    public class Bar
    {
         public void printMesg(String body)
         {
             System.out.println(body);
         }
    }
    public static void main(String[] args)
    {
         // Creating new instance of 'Bar' using Class.forname - how?
    }        
}

Is it possible to create new instance of class Bar giving its name? I tried to use:

Class c = Class.forName("Foo$Bar")

it finds the class, but when i use c.newInstance() it throws InstantiationException.

Answer

You need to jump through a few hoops to do this. First, you need to use Class.getConstructor() to find the Constructor object you want to invoke:

Returns a Constructor object that reflects the specified public constructor of the class represented by this Class object. The parameterTypes parameter is an array of Class objects that identify the constructor’s formal parameter types, in declared order. If this Class object represents an inner class declared in a non-static context, the formal parameter types include the explicit enclosing instance as the first parameter.

And then you use Constructor.newInstance():

If the constructor’s declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance

Categories
discuss

Unsubscribing a LocationListener from the LocationManager

How do I unsubscribe a LocationListener from recieving updates from the LocationManager?

Here is how I’m setting it up

mLocationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
mListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        Log.i("LocationListener", "Logging Change");
    }

}

mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                5000, 1, mListener);

After I have exited the the view that created the LocationListener I am still getting log messages in the LogCat window.

I understand that this is because I am orphaning the listener but I cannot see any destroy method on the LocationListener nor can I see any “remove listener” style methods on the LocationManager object.

Answer

Call removeUpdates on LocationManager, passing your location listener.

Categories
discuss

InetAddress.getByName on Android

I do a:

java.net.InetAddress serverAddr;
try {
    serverAddr = java.net.InetAddress.getByName(Server.SERVERNAME);
}
catch (java.net.UnknownHostException exception) {
    //System.err.println ("wrong server name !!!");
    HelloWorldActivity.tv.setText("wrong server name !!!");
    return;
}

in my android application, but it’s never resoling the hostname, it always throws an exception, no matter what name I use.


But using the internet on the same emulator works, and I’ve added

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

to AndoidManifest.xml

and here’s the server class for those who assume I have none

public class Server
{
    public static String SERVERNAME = "monster.idsoftware.com";
    public static String SERVERIP = "209.85.129.99";
    public static int SERVERPORT = 27950;
    public static int PROTOCOL = 68;
}

Answer

I’ve found the answer. For whatever reason, you have to use:

java.net.InetAddress[] x= java.net.InetAddress.getAllByName(Server.SERVERNAME) ; HelloWorldActivity.tv.setText("Address: "+x[0].getHostAddress());

Categories
discuss

How can I check the new value of a text field on keypress?

I have a single form field and I need to be able to detect when the field changes and execute some additional code using the new value of the field. I only want to execute the code if the key pushed actually changes the value of the text box. Here’s the solution I came up with.

function onkeypress(e) {
  var value = this.value;
  // do something with 
}

function onkeyup(e) {
  if ( e.which == 8 || e.keyCode == 46 ) { // delete or backspace keys
    this.onkeypress(e);
  }
}

There’s just one problem though. onkeypress is fired before the field’s value is updated, so when I grab the value, I’m getting the previous value. I would use keyup exclusively if I knew a way to test whether the key changed the value or not, but some characters (like the arrow keys) have no effect on the field’s value.

Any ideas?

Answer

The way I do this is simply with a variable along the lines of prevValue. At the end of the key press function, store the value in that variable, and only execute the function again if the value doesn’t equal that previous value.

Categories
discuss

Separation of concerns – DAO, DTO, and BO

So I have a DAO, DTO, and BO. The following code is the result:

// Instantiate a new user repository.
UserRepository rep = new UserRepository();

// Retrieve user by ID (returns DTO) and convert to business object.
User user = rep.GetById(32).ToBusiness<User>();

// Perform business logic.
user.ResetPassword();
user.OtherBusinessLogic("test");
user.FirstName = "Bob";

// Convert business object back to a DTO to save to the database.
rep.Save(user.ToDataTransfer<Data.DTO.User>());

So I am trying to separate concerns, but I want to get rid of the “converts” in this code. The “converts” are actually located in the business logic layer (DTO layer knows nothing of the business logic layer) as an extension object. The DTO itself obviously only stores data and has no business logic what-so-ever. The UserRepository calls the DAO and at the end of GetById uses AutoMapper to map from the DAO to DTO. The “converts” (ToBusiness and ToDataTransfer) do exactly as they say.

A colleague of mine thought I may have to have a Business Repository, but thought it might be a bit clunky. Any thoughts?

Answer

I resolved this by creating a Business Service layer. This way I can access functionality through the Business Service layer which in turn uses the Repositories which query the DAL and returns DTOs. The DTOs serve their purpose by being populated by the DAL and help transfer the data to the business layer (converted to business objects).

So the diagram is as follows:

DAL -> Repository (returns DTO) -> Service (returns BO)

It works very well and I am able to put business logic in the Service layer which abstracts it from the Repository itself. Sample code:

// UserService uses UserRepository internally + any additional business logic.
var service = new UserService();
var user = service.GetById(32);

user.ResetPassword();
user.OtherBusinessLogic("test");
user.FirstName = "Bob";

service.Save(user);
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..