Новичок
Профиль
Группа: Участник
Сообщений: 18
Регистрация: 11.4.2007
Репутация: нет Всего: нет
|
| Цитата(avvo @ 18.11.2007, 00:48) | | Цитата | If the underlying field is final, the method throws an IllegalAccessException unless setAccessible(true) has succeeded for this field and this field is non-static. Setting a final field in this way is meaningful only during deserialization or reconstruction of instances of classes with blank final fields, before they are made available for access by other parts of a program. Use in any other context may have unpredictable effects, including cases in which other parts of a program continue to use the original value of this field.
|
Короче static должен меняться без проблем. А вот с final может быть косяк. И если класс до этого уже использовался (дергались поля типа static final) то скорее всего JVM будет использовать старые значения.
В Config поле INTERNAL_HOSTNAME как объявлено? |
Ну как и положено: | Код | /** Internal Hostname */ public static String INTERNAL_HOSTNAME;
|
Короче, я хоть в инглише почти не рублю (а зря - сам знаю, лодырь - не учил в школе, а теперь сказывается...), но вот этот пример выдернул с документов по пакету java.lang.reflect | Код | import java.lang.reflect.*; public class field2 { public static double d; public static void main(String args[]) { try { Class cls = Class.forName("field2"); Field fld = cls.getField("d"); field2 f2obj = new field2(); System.out.println("d = " + f2obj.d); fld.setDouble(f2obj, 12.34); System.out.println("d = " + f2obj.d); } catch (Throwable e) { System.err.println(e); } } }
|
Как я понял - моя проблема в том, что я пытаюсь избежать прямого указания на Config (в примере Sun прямо указывается тип f2obj). Может переделка метода мне поможет (тока буду делать днём в это воскресенье или ближе к вечеру). Но я бы хотел сделать этот класс и подобные им не зависимыми, т.е. избежать прямого указания типа Config. Но как это сделать? Это уже выходит за рамки "отражения". Так что пытаясь сделать класс не зависимым и пытаясь избежать объявления new я получаю такие хреновые результаты... :( Класс Config содержет тока статистические поля и статистический метот load для загрузки данных из файла. Я его уже обеспечил кодом одноразового объявления (хоть пока не применяю его) | Код | public final class Config {
private static Config _instance; public static Config getInstance() { if (_instance == null) { _instance = new Config(); } return _instance; }
|
Вот короче весь Config | Код | /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. * * http://www.gnu.org/copyleft/gpl.html */ package loginserver.setup;
import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; import java.util.logging.Logger;
/** * This class containce global server configuration.<br> * It has static final fields initialized from configuration files.<br> * It's initialized at the very begin of startup, and later JIT will optimize * away debug/unused code. * * @author mkizub */ public final class Config {
private static Config _instance; public static Config getInstance() { if (_instance == null) { _instance = new Config(); } return _instance; } protected static final Logger _log = Logger.getLogger(Config.class.getName());
/** Debug/release mode */ public static boolean DEBUG;
/** Enable/disable assertions */ public static boolean ASSERT;
/** Enable/disable code 'in progress' */ public static boolean DEVELOPER;
/** Login Server port */ public static int PORT_LOGIN;
/** Login Server bind ip */ public static String LOGIN_BIND_ADDRESS;
/** Number of login tries before IP ban gets activated, default 10 */ public static int LOGIN_TRY_BEFORE_BAN;
/** Number of seconds the IP ban will last, default 10 minutes */ public static int LOGIN_BLOCK_AFTER_BAN;
// Access to database /** Driver to access to database */ public static String DATABASE_DRIVER;
/** Path to access to database */ public static String DATABASE_URL;
/** Database login */ public static String DATABASE_LOGIN;
/** Database password */ public static String DATABASE_PASSWORD;
/** Maximum number of Statements to the players */ public static int DATABASE_MAXSTATEMENTS;
/** Maximum number of connections to the database */ public static int DATABASE_MAX_CONNECTIONS;
/** Maximum PoolSize */ public static int DATABASE_MIN_POOLSIZE;
/** Minimum PoolSize */ public static int DATABASE_MAX_POOLSIZE;
/** If Pool Is Exhausted, Get 1 More Connections At A Time */ public static int DATABASE_ACQUIREINCREMENT;
/** Test Idle Connection Time */ public static int DATABASE_IDLECONNECTIONTEST;
/** Max Idle Time */ public static int DATABASE_MAXIDLETIME;
/*************************************************************************** * GM CONFIG General GM AccessLevel * **************************************************************************/
/** General GM Minimal AccessLevel */ public static int GM_MIN;
/** Datapack root directory */ public static File DATAPACK_ROOT;
// Configuration files /** * Properties file that allows selection of new Classes for storage of World * Objects. <br> * This may help servers with large amounts of players recieving error * messages related to the <i>L2ObjectHashMap</i> and <i>L2ObejctHashSet</i> * classes. */ /** Properties file for game server (connection and ingame) configurations */ public static final String CONFIGURATION_FILE = "./config/server.properties";
/** Properties file for login server configurations */ public static final String LOGIN_CONFIGURATION_FILE = "./config/loginserver.properties";
/** Properties file for telnet configuration */ public static final String TELNET_FILE = "./config/telnet.properties";
/** Text file containing hexadecimal value of server ID */ public static final String HEXID_FILE = "./config/hexid.txt";
/** Game Server login port */ public static int GAME_SERVER_LOGIN_PORT;
/** Game Server login Host */ public static String GAME_SERVER_LOGIN_HOST;
/** Internal Hostname */ public static String INTERNAL_HOSTNAME;
/** External Hostname */ public static String EXTERNAL_HOSTNAME;
/** Time between 2 updates of IP */ public static int IP_UPDATE_TIME;
/** Is telnet enabled ? */ public static Boolean IS_TELNET_ENABLED;
/** * Show licence or not just after login (if false, will directly go to the * Server List */ public static boolean SHOW_LICENCE;
/** Force GameGuard authorization in loginserver */ public static boolean FORCE_GGAUTH;
/** Accept new game server ? */ public static boolean ACCEPT_NEW_GAMESERVER;
/** Accept alternate ID for server ? */ public static boolean ACCEPT_ALTERNATE_ID;
/** ID for request to the server */ public static int REQUEST_ID;
/** Allow auto-create account ? */ public static boolean AUTO_CREATE_ACCOUNTS;
public static boolean FLOOD_PROTECTION;
public static int FAST_CONNECTION_LIMIT;
public static int NORMAL_CONNECTION_TIME;
public static int FAST_CONNECTION_TIME;
public static int MAX_CONNECTION_PER_IP;
/** * This class initializes all global variables for configuration.<br> * If key doesn't appear in properties file, a default value is setting on * by this class. * * @see CONFIGURATION_FILE (propertie file) for configuring your server. */ public static void load() { _log.info("loading login config"); try { Properties serverSettings = new Properties(); InputStream is = new FileInputStream(new File( LOGIN_CONFIGURATION_FILE)); serverSettings.load(is); is.close();
GAME_SERVER_LOGIN_HOST = serverSettings.getProperty( "LoginHostname", "*"); GAME_SERVER_LOGIN_PORT = Integer.parseInt(serverSettings .getProperty("LoginPort", "9013"));
LOGIN_BIND_ADDRESS = serverSettings.getProperty( "LoginserverHostname", "*"); PORT_LOGIN = Integer.parseInt(serverSettings.getProperty( "LoginserverPort", "2106"));
DEBUG = Boolean.parseBoolean(serverSettings.getProperty("Debug", "false")); DEVELOPER = Boolean.parseBoolean(serverSettings.getProperty( "Developer", "false")); ASSERT = Boolean.parseBoolean(serverSettings.getProperty("Assert", "false"));
ACCEPT_NEW_GAMESERVER = Boolean.parseBoolean(serverSettings .getProperty("AcceptNewGameServer", "True")); REQUEST_ID = Integer.parseInt(serverSettings.getProperty( "RequestServerID", "0")); ACCEPT_ALTERNATE_ID = Boolean.parseBoolean(serverSettings .getProperty("AcceptAlternateID", "True"));
LOGIN_TRY_BEFORE_BAN = Integer.parseInt(serverSettings.getProperty( "LoginTryBeforeBan", "10")); LOGIN_BLOCK_AFTER_BAN = Integer.parseInt(serverSettings .getProperty("LoginBlockAfterBan", "600")); GM_MIN = Integer.parseInt(serverSettings.getProperty("GMMinLevel", "100"));
DATAPACK_ROOT = new File(serverSettings.getProperty("DatapackRoot", ".")).getCanonicalFile(); // FIXME: in login?
INTERNAL_HOSTNAME = serverSettings.getProperty("InternalHostname", "localhost"); EXTERNAL_HOSTNAME = serverSettings.getProperty("ExternalHostname", "localhost");
DATABASE_DRIVER = serverSettings.getProperty("Driver", "com.mysql.jdbc.Driver"); DATABASE_URL = serverSettings.getProperty("URL", "jdbc:mysql://localhost/l2jdb"); DATABASE_LOGIN = serverSettings.getProperty("Login", "root"); DATABASE_PASSWORD = serverSettings.getProperty("Password", "");
DATABASE_MAX_CONNECTIONS = Integer.parseInt(serverSettings .getProperty("MaximumDbConnections", "50")); DATABASE_MAXSTATEMENTS = Integer.parseInt(serverSettings .getProperty("MaximumStateMents", "100")); DATABASE_MIN_POOLSIZE = Integer.parseInt(serverSettings .getProperty("MinPoolSize", "50")); DATABASE_MAX_POOLSIZE = Integer.parseInt(serverSettings .getProperty("MaxPoolSize", "10")); DATABASE_ACQUIREINCREMENT = Integer.parseInt(serverSettings .getProperty("AquireIncrement", "1")); DATABASE_IDLECONNECTIONTEST = Integer.parseInt(serverSettings .getProperty("IdleConnectionTest", "10800")); DATABASE_MAXIDLETIME = Integer.parseInt(serverSettings.getProperty( "MaxIdleTime", "0"));
SHOW_LICENCE = Boolean.parseBoolean(serverSettings.getProperty( "ShowLicence", "true")); IP_UPDATE_TIME = Integer.parseInt(serverSettings.getProperty( "IpUpdateTime", "0")); FORCE_GGAUTH = Boolean.parseBoolean(serverSettings.getProperty( "ForceGGAuth", "false"));
AUTO_CREATE_ACCOUNTS = Boolean.parseBoolean(serverSettings .getProperty("AutoCreateAccounts", "True"));
FLOOD_PROTECTION = Boolean.parseBoolean(serverSettings.getProperty( "EnableFloodProtection", "True")); FAST_CONNECTION_LIMIT = Integer.parseInt(serverSettings .getProperty("FastConnectionLimit", "15")); NORMAL_CONNECTION_TIME = Integer.parseInt(serverSettings .getProperty("NormalConnectionTime", "700")); FAST_CONNECTION_TIME = Integer.parseInt(serverSettings.getProperty( "FastConnectionTime", "350")); MAX_CONNECTION_PER_IP = Integer.parseInt(serverSettings .getProperty("MaxConnectionPerIP", "50")); } catch (Exception e) { e.printStackTrace(); throw new Error("Failed to Load " + CONFIGURATION_FILE + " File."); } } }
|
Реализую всю это байду по степенно используя разные классы, но вот главный пораждаемый main: | Код | package loginserver.setup.интерфейс;
import java.awt.BorderLayout; import javax.swing.JFrame; import loginserver.setup.Config;
public final class Пользовательский_Интерфейс extends JFrame { /** Версия интерфейса */ private static final long serialVersionUID = 1L; int ПозицияПоУмолчанию_Х = 200; int ПозицияПоУмолчанию_У = 200; int РазмерПоУмолчанию_Х = 700; int РазмерПоУмолчанию_У = 500;
public Пользовательский_Интерфейс() { Config.load(); Визуальный_Интерфейс(); } /**Создание оформления визуального интерфейса для администратора сервера */ private void Визуальный_Интерфейс() { setTitle("Конфигурация Логин сервера"); // название окна setLocation(ПозицияПоУмолчанию_Х, ПозицияПоУмолчанию_У); //позиция окна setSize(РазмерПоУмолчанию_Х, РазмерПоУмолчанию_У); //размер окна Главное_меню Меню = new Главное_меню(); //объявление меню setJMenuBar(Меню); // добавления меню к окну /* Кнопки быстрого переключения */ /*Быстрые_кнопки БКпанель= new Быстрые_кнопки(); add(БКпанель, BorderLayout.SOUTH);*/ /* Панель со вкладками */ Главная_панель Панель = new Главная_панель(); add(Панель, BorderLayout.CENTER); OK_and_Cansel OKПанель = new OK_and_Cansel(Панель_Подключения.getInstance()); add(OKПанель, BorderLayout.SOUTH); } }
|
Панель OK_and_Cansel и содержет процедуру опроса компонентов панели на принадлежность к L2JTextField. Как говорил - с этим проблем нету - всё вызывает правельно. Это сообщение отредактировал(а) Empire - 18.11.2007, 01:42
|