JAVA myString ['name'] = "my value"; (like in php)

In Php, I really often use this one:

$conn_sets = array();
$conn_sets['login'] = "aaa";
$conn_sets['pass'] = "bbb";

How to do the same in JAVA 1.6. I tried to do this:

private method1() {    
    String[] mystring = new String[] {"login" => "aaa", "pass" => "bbb"};
}

But that gives me an error. I want to make this work because I have error list declarations, and it’s better to define:

throw new MyException(myerrors['failed_login_error']);

than a:

throw new MyException(myerrors[116]);

I know that I can make a new class and throw away the object:

throw new MyException(ERROR_CONSTANTS.FAILED_LOGIN_ERROR);

But I prefer the first (same as in Php).

So any ideas?

+3
source share
4 answers

In Java, you probably want to use a map interface like HashMap .

, , Enum - , ( ), PHP, Java. , .

+14

Properties ( ResourceBundle ) .

tutorial.

, (I18N) ( ), , ( , , ).

+6

:

Map<String, String> map = new HashMap<String, String>() {{
    put( "login", "aaa" );
    put( "pass", "bbb" );
}};

... :

throw new MyException( myErrors.get( "failed_login_error" ) );
+4

HashMap Properties . - , :

String username = "aaa";
String password = "bbb";
Account acc = new Account(username,password);
if (!tryLogin(acc)) {
 throw new LoginFailedException(account);
}

This way, clients who catch LoginFailedExceptioncan use this information and use statically typed methods with good names, for example, to get the username by calling loginFailedException.getUsername().

+4
source

Source: https://habr.com/ru/post/1725741/


All Articles